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?
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With