0

I have this XMLHttpRequest library:

function easyHTTP() {
  this.http = new XMLHttpRequest();
}

// Make an HTTP POST Request
easyHTTP.prototype.post = function(url, data, callback) {
  this.http.open('POST', url, true);
  this.http.setRequestHeader('Content-type', 'application/json');

  let self = this;
  this.http.onload = function () {
    callback(null, self.http.responseText);
  }

  this.http.send(JSON.stringify(data));
}

At my HTML I have a button tag with id="btn", I want to send some data to a PHP file (named "ajax.php") when I click this button, so I have:

document.addEventListener("DOMContentLoaded", function() { 
      
      const http = new easyHTTP();

      // Create Data 
      const data = {
        title: 'Custom Posts',
        body: 'This is a custom post1'
      };

      document.getElementById('btn').addEventListener('click', function(e){

        // Create Post
        http.post('ajax.php', data, function(err, response){
          if(err) {
            alert(err);
          } else {
            alert(response);
          }
        });

        e.preventDefault();
      });

      
    });

And at my "ajax.php" I have:

<?php 

if($_SERVER['REQUEST_METHOD'] == "POST") {

  echo var_dump(json_encode($_POST));

}

?>

But all I get from return is an empty array, it should not come as the response the data that I sent? (Const data with "title" and "body")? What I'm doing wrong?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Julio W.
  • 149
  • 1
  • 2
  • 8

1 Answers1

0

It seems that XMLHttpRequest doesn't send the body to $_POST but rather to 'php://input'.

So instead of:

json_encode($_POST)

you can use:

file_get_contents('php://input')

Note that the result is still in JSON format.

  • Please note that this is the solution given in the marked duplicate. When questions are duplicates, they should be closed as such, instead of answered again. – Patrick Q Sep 12 '18 at 15:08