简体   繁体   中英

ajax call to PHP data returns VM92:1 Uncaught SyntaxError: Unexpected token {

Can anyone point me in the right direction as of why I receive an unexpected token "}" from this ajax call? I have checked for any extra character to my errors, but I have not found any. My JSON doesn't validate online, but this doesn't make sense due to me not manually creating the JSON. The error happens in VM98 if that means anything to someone. Any help would be much appreciated.

$.ajax({
    cache: 'false',
    type: 'GET',
    dataType: "json",
    url: 'list.php',
    success: function(result){
        var list = JSON.parse(result);
        console.log(list);

   },
   error: function(){
       console.log('error');
   }
});
<?php
$sql = "SELECT * FROM lists";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_object()) {
        $json_user = json_encode($row);
        echo $json_user;
    }
} else {
    echo "0 results";
}

You are concatenating multiple JSON string together which is not a valid JSON string.

Your JSON looks something like:

{"key":"value1"}{"key":"value2"}{"key":"value3"}

You need to put all the rows into an array and encode that into JSON.
Instead of echoing each row in a while loop, you can fetch all the rows in a single call and echo that JSON encoded data.

echo json_encode($result->fetch_all(MYSQLI_ASSOC));

This should produce something like:

[{"key":"value1"},{"key":"value2"},{"key":"value3"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM