Skip to content Skip to sidebar Skip to footer

Javascript Json.parse: Unexpected Character Error

I want to get a string from a php script, and parse it to a javascript array. but got the error : SyntaxError: JSON.parse: unexpected character for the line :JSON.parse(msg); I sea

Solution 1:

Don't parse it : $.ajax parsed it for you. Just use the argument which is given to your success callback, this is the parsed array.

If your browser can't detect it's JSON, add the dataType argument.

Note also that you don't have to manage the i counter yourself : one is passed by each :

dataType: 'json',
success: function(sum){
    $('input.hj').each(function(i){
        if (sum[i] > 0) {
            $(this).val(sum[i]);
        }
    });
}

Solution 2:

There's no need to parse it. Also, in your PHP script, your header should be:

header("Content-type: application/json; charset=utf-8");

In your JS, if price is a string (or float or int), there is no need to send it as json. For simplification, you may want to remove contentType: "application/json; charset=utf-8",,

Post a Comment for "Javascript Json.parse: Unexpected Character Error"