user471317
user471317

Reputation: 1231

PHP - How to read post data with no key?

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

Answers (3)

meb5
meb5

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

Kranu
Kranu

Reputation: 2567

Step 1 (Javascript code):

Instead of:

$.post("phppage", json, function(data) {
    alert(data);
});

Make it:

$.post("phppage", 'json':json, function(data) {
    alert(data);
});

Step 2 (PHP code):

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

Explosion Pills
Explosion Pills

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

Related Questions