phantom phantom - 4 months ago 8
Javascript Question

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 AJAX

GET
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 jquery
GET
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 says
error
, meaning it has executed the
error
function.

When I load the php file in the browser it displays the following.

{"name":"Peter"}{"name":"Alan"}{"name":"Mike"}

Answer

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,

if ($result->num_rows > 0) {
    $return = array();
    while($row = $result->fetch_assoc()) {
        $return[] = array('customer' => $row["name"]);
    }
    echo json_encode($return);
} else {
    echo "0 results";
} 
Comments