Flion
Flion

Reputation: 10902

Why does jQuery.post end up in PHP's $_POST, and my vanilla JS post does not?

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?

Upvotes: 4

Views: 386

Answers (1)

adeneo
adeneo

Reputation: 318192

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

Upvotes: 8

Related Questions