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?