Post Works With Jquery But Does Not Work With Xmlhttprequest
Solution 1:
Do not confuse JavaScript objects with JSON.
If you pass an object to jQuery's data
parameter then it will encode it as application/x-www-form-urlencoded
data (not JSON!).
If you POST application/x-www-form-urlencoded
data to PHP then it will parse it and populate the $_POST
superglobal with it.
If you pass an object to the send()
method of an XMLHttpRequest
object then it will not encode it for you. It will invoke .toString()
on it implicit and send nothing very useful at all.
To achieve the same effect as jQuery will do then you need to encode the data yourself. Don't forget to also set the Content-Type
header!
const encoded = newURLSearchParams(Object.entries(msg)).toString();
const xhr = newXMLHttpRequest();
xhr.open("POST", phpURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(encoded);
If you want to send JSON then you also have to encode it, but that is done simply with JSON.stringify()
although you also need to set the Content-Type header (to application/json
this time).
const encoded = JSON.stringify(msg);
const xhr = newXMLHttpRequest();
xhr.open("POST", phpURL, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(encoded);
However, PHP will not parse JSON automatically so $_POST
will remain empty, so you need to parse it manually.
<?php$json = file_get_contents('php://input');
$msg = json_decode($json);
Solution 2:
jQuery does a lot of work under the hood when sending an AJAX request. It converts a live object in application/x-www-form-urlencoded format and fixes the headers, and does other tasks depending on the arguments.
When you're sending a native XMLHttpRequest, you've to handle all this by yourself. In the comments you said, you actually want to send JSON. JSON is not a standard form content type PHP would recognize, hence you've to send it in application/json format. Like this:
var msg = {
name: 'joe',
message: 'why no work'
},
xhr = newXMLHttpRequest();
xhr.open('POST', phpURL, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// Add response handling here, if needed
xhr.send(JSON.stringify(msg));
However, content type of application/json is not considered as form data in PHP, and $_POST
will be empty. You can read the data from the received raw data, which is saved in a specific file. Like this:
$data = file_get_contents('php://input');
// Results a string: '{"name":"joe","message":"why no work"}'
Now you can convert the JSON to associative array with json_decode($data)
.
Post a Comment for "Post Works With Jquery But Does Not Work With Xmlhttprequest"