An XMLHTTP request that passes a JSON string as input

My JavasSript sends a 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); } } 

Now all my php are:

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

The output from the source data is an object string, but the mail array is empty.

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

I need to get it in the correct format for the $_POST variable, and jquery is not an option.

+4
source share
2 answers

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

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

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

BTW: Never, ever use the forbidden death death suffix: @ . Mistakes are there to help you, not annoy you ...

+6
source

You need to get the source 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.

0
source

Source: https://habr.com/ru/post/1486289/


All Articles