4

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??

2 Answers2

3

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.

Michal Hynčica
  • 2,925
  • 1
  • 4
  • 17
  • Hi Michal, i'm trying with file_get_contents("php://input") but still output is null. Seems PHP doesn't catch anything... – Jorge del Campo Andrade Oct 03 '19 at 12:13
  • I've added an example code for the `file_get_contents` approach that works for me. You also need to transform the data into string with `JSON.stringify()`. – Michal Hynčica Oct 03 '19 at 12:36
  • Hi Michal, just one more question. Why with $.post (jquery) is possible send POST data to PHP but no with XMLHttpRequest json? – Jorge del Campo Andrade Oct 05 '19 at 11:30
  • It's because of how the data are sent to server. JQuery's $.post is sending data as `application/x-www-form-urlencoded` instead of json and that's why php parses the recieved data into `$_POST` variable. You can also send request with `XMLHTtpRequest` as `application/x-www-form-urlencoded` and you will be able to find the data in `$_POST`. See the question i've linked in my answer to see how to do that. – Michal Hynčica Oct 05 '19 at 15:23
  • Thanks Michael! Now with this explanation i understand the page you've linked. :) – Jorge del Campo Andrade Oct 05 '19 at 16:05
0

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);
Aakash Tushar
  • 456
  • 3
  • 18