Answer the question
In order to leave comments, you need to log in
Why doesn't PHP accept JSON sent via AJAX?
Sorry if this is a dumb question, I've been looking for a solution but haven't found anything yet. I'm most likely missing something.
Problem:
I'm using AJAX to send data using the POST method to a php file, the object is converted to json:
const body = {
name: 'ilya',
email: '[email protected]'
}
let xhr = new XMLHttpRequest();
xhr.open('POST', 'newtest.php');
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(body))
<?php
$input = json_decode(file_get_contents("php://input"), true);
print_r($input);
?>
Answer the question
In order to leave comments, you need to log in
Do like this:
async function sendPOST() {
try {
var formData = new FormData();
formData.append('name', 'Илья');
formData.append('email', '[email protected]');
var response = await (await fetch('newtest.php', {
method: 'POST',
body: formData
})).text();
console.log("POST-запрос отправлен успешно. Ответ сервера:\n" + response);
return response;
}
catch (err) {
console.log('При отправке POST-запроса произошла ошибка:');
console.dir(err);
return false;
}
}
sendPOST()
<?php
print_r($_POST);
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question