4

My JavasSript sends the request:

var jax = new XMLHttpRequest();
jax.open("POST", "http://localhost/some.php", true);
jax.setRequestHeader("Content-Type", "application/json");
jax.send(JSON.stringify(jsonObj));
jax.onreadystatechange = function() {
    if(jax.readyState === 4) { console.log(jax.responseText);  }
}

Right now all my php does is:

print_r($HTTP_RAW_POST_DATA);
print_r($_POST);

The output from the raw post data is the object string, but the post array is empty.

{"name" : "somename", "innerObj" : {} ... }
Array
(
)

I need to get it in the proper format for the $_POST variable, and jquery isn't an option.

Rob W
  • 341,306
  • 83
  • 791
  • 678
Amos47
  • 695
  • 6
  • 15

2 Answers2

6

Right, since user1091949 posted my comment as an answer, here's the same thing again, so OP can choose who's answer to approve (if it worked):

$json = json_decode(file_get_contents('php://input'));

At this point, $json will be an instance of the stdClass... If you prefer an associative array, just pass a second parameter to json_decode('{"json":"string"}', true);

BTW: Never, Ever use the forbidden error-suppressor of death: @. Errors are there to help you, not to annoy you...

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
0

You need to get the raw post data:

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  exit;
}

$postdata = @file_get_contents("php://input");
$json = json_decode($postdata, true);

$json will be an associative array containing your JSON data.

user1091949
  • 1,933
  • 4
  • 21
  • 27