$_POST is empty while Request Payload shows data, XMLHttpRequest

Have a good day!

I’m using a JavaScript function to call a self-made php page via the post method, the $_POST variable remains empty though.

I’m pretty new into PHP world and my problem might be a bit silly, but it’s been 48 hours that I’m trying to debug this and while browsing there where so much similar problems but neither solved mine.

The code is pretty complicated, but I simplified the code to debug the problem, but still it occurs.

JS function

function save() {
              var xhr = new XMLHttpRequest();
              xhr.open("POST", "gameapi.php/", true);
              xhr.setRequestHeader('Accept', 'application/json',);
              xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
                'saving': 1
              xhr.onload = function() {


      echo var_dump($_POST);

As you can surely guess this is not the original code, and is simplified, but still the response is an empty array.

I also have tried the code without RequestHeaders.

I’m expecting that $_POST['saving'] include 1 but it $_POST is an empty array.

Also, in Inspect’s Network tab the request is sent successfully, and I’m pretty sure that the url or anything is correct.


{saving: 1}


<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
  <i><font color='#888a85'>empty</font></i>

I’m using Firefox and local host

>Solution :

$_POST documentation (php.net)

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

In your case (application/json) you will not receive an associative array.

You can try to use php://input instead:

php://input is a read-only stream that allows you to read raw data from the request body. php://input is not available in POST requests with enctype="multipart/form-data" if enable_post_data_reading option is enabled.

$data = json_decode(file_get_contents('php://input'), true);

Leave a Reply