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