Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 396
Flion Avatar asked Jan 10 '23 04:01

Flion


1 Answers

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

like image 167
adeneo Avatar answered Jan 18 '23 23:01

adeneo