Reputation: 1946
I'm using jQuery and jquery-json to post data to a PHP script.
$.post('<?php echo url_for('/ajax.php'); ?>', 'data=' + $.toJSON(order), function (response) {
if (response == "success") {
$("#respond").html('<div class="success">Item Saved!</div>').hide().fadeIn(1000);
setTimeout(function () {
$('#respond').fadeOut(1000);
}, 2000);
}
})
If I console.log(order) I get the following JOSN:
{"details":[{"template_id":"25","font_size":"22"}]}
In my ajax.php file I have:
$data = json_decode($_POST["data"]);
var_dump($data);exit;
Which returns 'NULL'
But when I have the following code:
$data = $_POST["data"];
var_dump($data);exit;
It returns:
string(61) "{\"details\":[{\"template_id\":\"25\",\"font_size\":\"26\"}]}"
Is there any reason why it is escaped?
What is the easiest way to decode this?
Thanks
Upvotes: 1
Views: 1826
Reputation: 253
You need to add dataType: 'json' to your ajax call.
$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: $.toJSON(order),
async: true,
success: function (data) {
if (data.response) {
$("#respond").html('<div class="success">Item Saved </div>').hide().fadeIn(1000);
setTimeout(function () {
$('#respond').fadeOut(1000);
}, 2000);
}
}
});
Upvotes: 0
Reputation: 19888
you may need to disable magic_quotes_gpc
in your php.ini or .htaccess file which is adding the slashes to your post variables.
Or you could just call stripslashes
on $_POST['data'] like so:
$data = json_decode(stripslashes($_POST["data"]));
Upvotes: 1