Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseJSON error: unexpected character at line 1 column 2 of the JSON data

I have a PHP script like so:

$STL = array();
$filter = array();
$filter['sort_by'] = "date_added";
$filter['sale'] = "F";
$filter['per_page'] = "12";
$STL['filter'] = $filter;
echo json_encode($STL);

This gives the following output:

{"filter":{"sort_by":"date_added","sale":"F","per_page":"12"}}

I am trying to use parseJSON like so:

$.ajax({ 
    url: 'myPHP.php',
    type: 'post',
    data : get_session,
    async: false,
    dataType: 'json',
    success: function(result) {
        var json = $.parseJSON(result);         
    } 
});

But I get the following result:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

I'm guessing the json string isn't formatted correctly in the PHP. What I got wrong?

like image 791
Lee Avatar asked Dec 14 '25 15:12

Lee


1 Answers

When you specify dataType: 'json' (or jQuery detects a JSON response) then it will automatically parse the JSON for you. If you then attempt to again parse the resulting object you get the error you are seeing. Your result parameter of the success function is already an object you can work with.

Also note that you should never use async: false. It is horrendous practice to use it as it blocks the UI thread until the AJAX request completes. This looks to the user like the browser has crashed. Remove that property from the settings and place all code reliant on the AJAX result in the success handler.

Try this:

$.ajax({ 
    url: 'myPHP.php',
    type: 'post',
    data : get_session,
    dataType: 'json',
    success: function(result) {
        console.log(result);      
    } 
});
like image 167
Rory McCrossan Avatar answered Dec 16 '25 05:12

Rory McCrossan