Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read associative array from json in $_POST

Tags:

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

<?php
$value = json_decode(stripcslashes($_POST));
echo $value['page'];
?>

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

like image 828
Daniel Avatar asked Apr 27 '11 15:04

Daniel


2 Answers

$_POST will not be populated if the request body is not in the standard urlencoded form.

Instead, read from the read-only php://input stream like this to get the raw request body:

$value = json_decode(file_get_contents('php://input'));
like image 57
Evert Avatar answered Oct 09 '22 21:10

Evert


You can avoid to use JSON.stringify and json_decode:

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

And:

<?php
echo $_POST['page'];
?>

Update:

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

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

And:

<?php
$value = json_decode($_POST['json']);
echo $value->page;
?>
like image 20
Francesco Terenzani Avatar answered Oct 09 '22 21:10

Francesco Terenzani