Search code examples
javascriptphpjsonxmlhttprequest

Unable to parse JSON (xmlhttp)


I've gone through literally all of the other questions on this topic but I can't seem to find a fix for this relatively easy problem:

console.log(xmlhtpp.responseText) results in:

[{"id":"1","name":"Filosofie","image":"yin-yang.png","background_color":"no"},{"id":"2","name":"Politiek","image":"politics.png","background_color":"no"},{"id":"3","name":"Geschiedenis","image":"history.png","background_color":"no"},{"id":"4","name":"Vocabulaire","image":"vocabulary.png","background_color":"no"},{"id":"5","name":"Wetenschap","image":"science.png","background_color":"no"}]

The problem occurs when I try to parse the string to an object like so:

JSON.parse(xmlhttp.responseText);

Which results in the following error:

Uncaught SyntaxError: Unexpected end of input

The string originates from a PHP file:

$results = $db->query("SELECT * FROM library ORDER BY id", true);   

$categories = array();

while ($row = mysqli_fetch_assoc($results)) {
    $categories[] = $row;
}

echo json_encode($categories);

I need to loop trough the object eventually but I can't get past the parsing, any advice would be very much appreciated.


Solution

  • The default Content-Type from XAMPP is text/html, so your browser is trying to parse it like this..

    Set the content-type yourself..

    header('Content-Type: text/javascript');
    echo json_encode(["foo", "bar"]);