3

So I'm posting an array of objects in a JSON string using javascript to a PHP script and I'm having real problems decoding it in the php.

My javascript is as follows:

$.ajax({
    type: 'POST',
    url: "question_save.php",
    data: {myJson:  JSON.stringify(jsonArray)},
    success: function(data){

        alert(data);

    }
});

The string sent to the PHP looks like this:

[{"content":"Question text"},{"answerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerContent":"","score":"0","responseChecked":0,"responseContent":""}]

If I echo $_POST['myJson'] I get this:

[{\"content\":\"Question text\"},{\"answerContent\":\"Some answer text\",\"score\":\"234\",\"responseChecked\":0,\"responseContent\":\"\"},{\"answerContent\":\"\",\"score\":\"0\",\"responseChecked\":0,\"responseContent\":\"\"}]

Yet when I want to decode the JSON and loop through it like this...

$json = $_POST['myJson'];
$data = json_decode($json, true);

foreach ($data as &$value) {
    echo("Hi there");
}

...I get this error:

Warning:  Invalid argument supplied for foreach() in /home/thecrime/public_html/test1/question_save.php on line 15

I really don't understand what silly mistake I'm making, is it something to do with the back slashes?

Any help much appreciated!

Thanks, -Ben

1
  • print $data values and see what is the value for this variable after json_decode ...
    – Riz
    Oct 24, 2011 at 9:03

2 Answers 2

18

Use stripslashes ( $string ) - http://php.net/manual/en/function.stripslashes.php

This should work

$json = $_POST['myJson'];
$json_string = stripslashes($json)
$data = json_decode($json_string, true);

// simple debug
echo "<pre>";
print_r($data);

However, as already pointed by the others, it's better to disable magic_quotes_gpc.

Open your php.ini file and search for this row:

magic_quotes_gpc = On

Set it to Off and restart the server.

2
  • Simone you are my savior and I love you. Thanks! :D
    – bbeckford
    Oct 24, 2011 at 9:15
  • 1
    Although obviously a valid answer, this is fighting the symptoms instead of the cause: magic_quotes_gpc. Turn them off, and you'll never have to worry about stuff like this again. Oct 24, 2011 at 9:20
3

This has to do with Magic Quotes
Is better to disable this annoying old feature and forget those problems.
You can disabled following these instructions.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.