I trying to send POST data to PHP file using XMLHttpRequest. The URL is right but PHP can't catch any of sent data and just back a null response.
I'm using pure javascript from client and PHP 7.1 on server
My PHP:
$data->msg = 'PHP is working';
$data->user = $_POST['user'];
$data->pass = $_POST['pass'];
echo json_encode($data);
My Javascript:
var data = { 'user': 'myUser', 'pass': 'myPass' };
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myurl', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var res = JSON.parse(xhr.response);
console.log(res);
}
};
xhr.send(data);
// Expected output: {msg: "PHP is working", user: myUser, pass: myPass}
// But just recive: {msg: "PHP is working", user: null, pass: null}
I expect this response: {msg: "PHP is working", user: myUser, pass: myPass} But just recive this: {msg: "PHP is working", user: null, pass: null}
As you can see PHP $_POST can't catch my sent post data and just back null. What's worng??
The problem is in your Content-Type. If you use application/json
the PHP won't parse the post data into $_POST variable. You have to send them as form data to have PHP parse it.
See this question for more info Send POST data using XMLHttpRequest
Alternatively you can use file_get_contents("php://input")
to get the raw body of HTTP request and parse the json with json_decode
.
Example with file_get_contents and json_decode
PHP Code:
$in = file_get_contents('php://input');
$decoded = json_decode($in, true);
$data = new stdClass();
$data->msg = 'PHP is working';
$data->user = $decoded['user'];
$data->pass = $decoded['pass'];
echo json_encode($data);
JS Code:
var data = { 'user': 'myUser', 'pass': 'myPass' };
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myUrl', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var res = JSON.parse(xhr.response);
console.log(res);
}
};
xhr.send(JSON.stringify(data));
return false;
Please notice that you need to JSON.stringify
the data object before passing it as argument to send()
method. Otherwise the data are not send correctly.
To receive json in php you need to read request body:
$request = json_decode(file_get_contents('php://input'), true);
$data->msg = 'PHP is working';
$data->user = $request['user'];
$data->pass = $request['pass'];
echo json_encode($data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.