Reputation:
JSON.parse throws an "unexpected token" error when I try to parse multiple JSON objects. I have used this approach before, but only when the array involved one row of query results.
Any help would be greatly appreciated. Thank you
The Error
Uncaught SyntaxError: Unexpected token {
The JavaScript
if(window.XMLHttpRequest){
var request = new XMLHttpRequest();
} else {
var request = new ActiveXObject(microsoft.XMLHTTP);
}
request.open('POST', 'controllers/engineersOutput.php', true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.onreadystatechange = function(){
if((request.readyState==4) && (request.status==200 || request.status==304)) {
var str = request.responseText;
var data = JSON.parse(str);
console.log(data);
}
}
request.send();
The PHP
public function getEngineerDetails(){
include "connect.php";
$query = "SELECT * FROM `engineers`";
$result = mysqli_query($con, $query);
while($row=mysqli_fetch_assoc($result)){
$name = $row['name'];
$pic = $row['pic'];
$insertedEngs = array( "name"=>$name, "pic"=>$pic );
echo json_encode($insertedEngs);
}
}
Upvotes: 2
Views: 804
Reputation: 41885
Most likely your JSON string created from server is malformed because of the way you created it.
Don't construct the JSON string while inside the loop, construct and complete the array first, then finally encode:
public function getEngineerDetails() {
include "connect.php";
$query = "SELECT * FROM `engineers`";
$result = mysqli_query($con, $query);
// define a container first
$data = array();
while($row = mysqli_fetch_assoc($result)){
// while inside the loop
// construct the array first
$insertedEngs = array("name" => $row['name'], "pic" => $row['pic']);
$data[] = $insertedEngs; // continually push
}
// then encode output when done
echo json_encode($data);
}
Upvotes: 0
Reputation: 413702
It looks like your code is returning a sequence of JSON-encoded objects, and that's not going to be recognizable to a JSON parser. Collect your objects into an array (in the PHP code) and then echo the whole array via json_encode
when it's complete. Then your client will receive a JSON array.
Upvotes: 1