Reputation: 1231
This piece of jQuery code posts to one of our php pages.
var json = '{"object1":{"object2":[{"string1":val1,"string2":val2}]}}';
$.post("phppage", json, function(data) {
alert(data);
});
Inside phppage, I have to do some processing depending on the post data. But I am not able to read the post data.
foreach ($_POST as $k => $v) {
echo ' Key= ' . $k . ' Value= ' . $v;
}
Upvotes: 3
Views: 4741
Reputation: 51
use file_get_contents("php://input")
to capture the data received by your script when key=value
pairs are not used. This approach is common with jsonrpc APIs.
Upvotes: 5
Reputation: 2567
Instead of:
$.post("phppage", json, function(data) {
alert(data);
});
Make it:
$.post("phppage", 'json':json, function(data) {
alert(data);
});
Change to:
$json=json_decode($_POST['json']);
foreach($json as $k => $v) {
echo ' Key= ' . $k . ' Value= ' . $v;
}
or:
$json=json_decode($_POST['json']);
print_r($json);
Upvotes: 0
Reputation: 191729
What you have should work fine, but the JSON object is turned into an array of arrays when it is given to the POST data. You will get something like this:
["object1"]=>
array(1) {
["object2"]=>
array(1) {
[0]=>
array(2) {
["string1"]=>
string(4) "val1"
["string2"]=>
string(4) "val2"
}
}
}
}
So object1 is an array that holds all the other data. If you do
foreach ($_POST as $key => $val) {
echo $key . " > " . $val
}
It prints out "object1 > Array". In other words you need to iterate through the value as well. How you do this depends on how the data you are receiving is structured or whether you even know how it is structured.
Upvotes: 4