Daniel Daniel - 1 year ago 83
PHP Question

Read associative array from json in $_POST

I am using jQuery to post a json object to my php application.

jQuery.post("save.php",JSON.stringify(dataToSend), function(data){ alert(data); });

The json string as pulled from firebug looks like this

{ "data" : [ { "contents" : "This is some content",
"selector" : "DIV.subhead"
{ "contents" : "some other content",
"selector" : "LI:nth-child(1) A"
"page" : "about_us.php"

In php I am trying to turn this into an associative array.

My php code so far is

$value = json_decode(stripcslashes($_POST));
echo $value['page'];

The response to the ajax call should be "about_us.php" but it comes back blank.

Answer Source

You can avoid to use JSON.stringify and json_decode:

jQuery.post("save.php", dataToSend, function(data){ alert(data); });


echo $_POST['page'];


... but if your really want to use them, then:

jQuery.post("save.php",  {json: JSON.stringify(dataToSend)}, function(data){ alert(data); });


$value = json_decode($_POST['json']);
echo $value->page;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download