php, ajax and json encoding/decoding

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

Answers


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"]));

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);

      }

    }

});

Need Your Help

Check for pending changes when using WPF Explicit Binding

wpf data-binding

I have a modal popup that contains a CheckBox that uses Explicit binding to update binding source when the user clicks the save button on form.

use webkit-playsinline in javascript

javascript html5 video

How do I use webkit-playsinline in javascript instead of in html5 video tag? I want to use it just like using video tag control/autoplay attribute in javascript or if you guys have any other method...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.