SyntaxError: "JSON.parse: unexpected non-whitespace ..." when returning JSON from PHP SyntaxError: "JSON.parse: unexpected non-whitespace ..." when returning JSON from PHP json json

SyntaxError: "JSON.parse: unexpected non-whitespace ..." when returning JSON from PHP


Your JSON is not valid because it consists of multiple objects. What you need to do is put all your results into an array and then echo the json_encode of that. Try something like this:

    $records = array();    if ($result = mysqli_query($conn, $query)) {        while ($records[] = mysqli_fetch_assoc($result)) {        }    }    echo json_encode($records);

This will give you an output that looks something like this:

[    {"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"},    {"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}]

and you can access each of the elements in your Javascript by something like

let customer = data[0].FirstName + ' ' + data[0].LastName;