phantom phantom - 8 months ago 25
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

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
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.



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";


type: 'GET',
url: 'getcustomers.php',
success: function(data){
error: function() {

In the console it simply says
, meaning it has executed the

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



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";