3

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?

0

3 Answers 3

3

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);      
    } 
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh I get you! Rookie mistake by me there. Thats great stuff, thanks Rory.
3

If you're using $.parseJSON(result) already on success callback, then remove dataType: 'json', from AJAX properties.. Or use the another way by retaining dataType: 'json' as you expecting JSON already as a result and remove $.parseJSON(result). Use only either one.

Comments

1

the error
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
happens when your json object is not valid. for this case you can check your json by jsonlint,
but for this case,because of use dataType: 'json' on your ajax request,your output is already is the parsed of josn

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

$.parseJSON(result) turn string to JSON
your request response is already a valid JSON so, the $.parseJSON(string) return error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.