Unexpected end of input JSON.parse (PHP, JSON, jQuery.post, database)

3.7k Views Asked by At

I have a php-file which creates a json and passes it on to javascript

<?php
    $index = 0;
    $connection = mysql_connect(*secret*,*secret*,*secret*);
    mysql_select_db("sql7150348");
    $query =mysql_query("SELECT * FROM  statements");
    while ($row = mysql_fetch_assoc($query)) {
        $array[$index] = $row;
        $index++;
    }
    echo json_encode($array);

Then I recieve this data with $.post

[{
"Titel": "Begroting",
"Text": "In crisistijden mag de Vlaamse begroting in het rood gaan",
"Voor": "spa",
"Tegen": "vld",
"PuntVoor": 0,
"PuntTegen": 0
}]

$.post('../php/getFromDatabase.php', function () {}).done(function (data) {
    console.log(JSON.parse(data));
});

but i always get this error (about console.log(JSON.parse(data));)

Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at Object.success (script.js:20)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest. (jquery.min.js:4)

What did I do wrong to get this error?

1

There are 1 best solutions below

0
On BEST ANSWER

The client is not able to identify the type of response received by the server. Specifying response type JSON should fix it.

$.post('../php/getFromDatabase.php', function () {}).done(function (data) {
    console.log(data);
}, "json");