9

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
  • what is data is being passed on your network console? Oct 3, 2019 at 11:13
  • i would suggest to use "axios" for ajax requests, its better then vanilla javascript
    – Ilijanovic
    Oct 3, 2019 at 11:16

2 Answers 2

10

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.

5
  • Hi Michal, i'm trying with file_get_contents("php://input") but still output is null. Seems PHP doesn't catch anything... Oct 3, 2019 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(). Oct 3, 2019 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? Oct 5, 2019 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. Oct 5, 2019 at 15:23
  • Thanks Michael! Now with this explanation i understand the page you've linked. :) Oct 5, 2019 at 16:05
4

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);
2
  • Hi, i don't understand. Why $request ? I've try with your code but nothing Oct 3, 2019 at 12:11
  • $request is just a variable. I thought since you're receiving a request, $request name is right. btw do you see any data being sent in your network console? Oct 3, 2019 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.