I want to return a json array back to the calling $.ajax function, but I only get the last item of the expected array. Maybe I don't produce an array?
If I click the button with the id "btn_getAnswers" the "$("#btn_getAnswers").click" gets fired and the code of "DBCOMANSWERS" will be executed. I want "$result" in "DBCOMANSWERS" to be an array filled with the values of my MYSQL-Database. I return "$result" formatted as JSON. The returned result should append to the paragraph with the id "output". So far, that works fine, but I except three strings to be returned and appended to the paragraph, now just a single one, the last catched entry from the database, gets appended.
I dont really can see where i have to put a loop for appending or whatever. Is the returned $result maybe not an array just the last entry of database because it gets overwritten?
Index.html:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.12.3.js"></script> <!-- Import the jquery extension -->
<script>
$(document).ready(function () {
$("#btn_getQuestion").click(function () {
$.ajax({
type: "POST",
url: "DBCOMQUESTIONS.php?q=" + $("#input").val(),
success: function (result) { //Performs an async AJAX request
if (result) {
$("#output").html(result); //assign the value of the result to the paragraph with the id "output"
}
}
});
});
$("#btn_getAnswers").click(function () {
$.ajax({
type: "POST",
url: "DBCOMANSWERS.php?q=" + $("#input").val(),
success: function (result) { //Performs an async AJAX request
if (result) {
$("#output").append(result);
}
}
});
});
});
</script>
</head>
<body>
<p id="output">This is a paragraph.</p>
<input id="input"/>
<button id="btn_getQuestion">Question</button>
<button id="btn_getAnswers">Answers</button>
</body>
</html>
DBCOMANSWERS.php:
<!DOCTYPE HTML>
<head>
</head>
<body>
<?php
include("connection.php"); //includes mysqli_connent with database
include("ErrorHandler.php"); //includes error handling function
set_error_handler("ErrorHandler"); //set the new error handler
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement
$query = mysqli_query($con,$sql); // get the data from the db
while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
$result = $row['answer'];
}
echo json_encode($result); // return value of $result
mysqli_close($con); // close connection with database
?>
</body>
<html>
$row['answers']just returns strings.