Answer the question
In order to leave comments, you need to log in
Why isn't data sent via post?
(function () {
'use strict';
setTimeout(() => {
check();
}, 3000);
})();
async function check() {
try {
const response = await fetch('https://site.ru/script.php', {
method: 'POST',
body: JSON.stringify({yes: 'yes'}),
headers: {
'Content-Type': 'application/json'
}
});
console.log(response);
const json = await response.json();
console.log('Успех:', json);
} catch (error) {
console.error('Ошибка:', error);
}
}
Answer the question
In order to leave comments, you need to log in
To $_POST
be NOT empty, you must send data in encoding application/x-www-form-urlencoded
or multipart/form-data
. In your example, you are trying to send data in encoding application/json
, while doing it wrong.
Try like this:
window.addEventListener('load', check); // Запуск check после полной загрузки страницы
async function check() {
var data = {
'test': 'Привет, мир!',
'myname': 'Дмитрий'
};
var response = await (await fetch('https://site.ru/script.php', {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'body': new URLSearchParams(data).toString()
})).text();
console.log('Ответ сервера:', response);
return response;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question