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
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.
Use
stripslashes ( $string )
- http://php.net/manual/en/function.stripslashes.phpThis should work
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:Set it to
Off
and restart the server.