javascript - jQuery GET request to PHP failing although PHP is fetching the data
I having written a php script which makes an SQL query and fetches a list of unique names from the database.
I am making an AJAXGET
request using jQuery to the php script. When I check resources in the console I see that the php script is being called, and when I check the response it contains a list of unique names.
However, the jqueryGET
request is failing, and is displaying an error message in the console.
It may be easier and clearer to look at my code, as I have no idea what is the issue here. Please see code below.
php
<?php
header('Content-Type: application/json');
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT(name) FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo json_encode(array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
$conn->close();
?>
JS
$.ajax({
type: 'GET',
url: 'getcustomers.php',
success: function(data){
console.log(data);
},
error: function() {
console.log('error');
}
});
In the console it simply sayserror
, meaning it has executed theerror
function.
When I load the php file in the browser it displays the following.
{"name":"Peter"}{"name":"Alan"}{"name":"Mike"}
Answer
Solution:
Your JSON response is not a valid one. You are printing each data row on each iteration. So replace the while statement with this one,
Answer
Solution:
Considering your script returns any result (I hope you've tried running it in broswer) then you can use something like this:
Although, common errors because you must specify the directory path if the php file you're requesting is outside the current working directory.
Answer
Solution:
change your error handler function header to the following:
then print that and see what the error is
Answer
Solution:
you are echoing json_encode string in side while loop, instead of that you will have to push row in an array and at the end you can echo json string only once.