I'm using vanilla JavaScript to send a AJAX post request with JSON data:
xhr.open(method, url,true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
The headers look good, but in PHP $_POST
is empty. There are several related questions on SO about this, like this one, but they all suggest using:
json_decode(file_get_contents("php://input"))
However, if I use jQuery.post
my variables end up in $_POST
, so it must be possible. My question is how? What might I be doing wrong? Or what could I change?
That happens because jQuery converts the data you pass in to a string in the format of a form, with a application/x-www-form-urlencoded
header, which is something PHP recognizes and correctly creates the $_POST
superglobal from.
Your native XMLHttpRequest sends the data as a string in JSON format with the application/json
header, which PHP does not recognize as form data, and does not create a $_POST
array from.
In modern browsers you can use formData
to create valid form data that can be sent with ajax and recognized by PHP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With