1
I’m trying to create a sending function via Ajax with pure Javascript, but PHP does not receive the data.
Javascript is sending data correctly.
Javascript code:
this._data = JSON.stringify(data);
Object.freeze(this);
function reqListener() {
console.log(this.responseText);
};
let request = new XMLHttpRequest();
request.onload = reqListener;;
request.open('POST', '/api');
request.setRequestHeader('Content-Type', 'application/json;');
request.send(this._data);
I tried to use application/x-www-form-urlencoded also unsuccessful.
PHP code:
$jSon = array();
$getPost = file_get_contents('php://input');
$post = json_decode($getPost);
echo json_encode($jSon);
The purpose of these codes is to send a JSON via Ajax and PHP returns itself.
Does it give an error message? If not, it seems to me that your PHP code doesn’t make much sense. You give
echo
in the variable$jSon
, but it will always be an empty array. If you just want to echo the data, the correct would not be to pass the value of$post
for the functionjson_encode
? Something likeecho json_encode($post)
– Woss
@Andersoncarloswoss Either way it will be empty, because file_get_contents('php://input') is empty. This is my problem, the client shows that the data was sent, but back-end returns an empty array. The PHP code is just a test, from the moment it works I will start developing the application in s
– Weverton
And if you do
var_dump($_POST)
, what is the return?– Woss
@Andersoncarloswoss He returns
null
also, from what I read on the help pages, thefile_get_contents('php://input')
takes the raw data, while the$_POST
treats him. Because JSON is the$_POST
will always return null.– Weverton