3

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;
}

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.