1

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

1
  • i think variable "order" is already a json. Commented Jan 23, 2013 at 21:27

2 Answers 2

1

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

4 Comments

The function is called stripcslashes instead of stripslahses
stripslashes would do the job, but disabling magic_quotes_gpc is always the better solution if you are able to do it.
@P1nGu1n no, stripcslashes serves another purpose, to remove magic quotes, stripslashes is the right function.
Yeah it was a typo... I have disabled magic quotes and all seems fine.
0

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

      }

    }

});

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.