Answer the question
In order to leave comments, you need to log in
How to send data using the fetch method and get the correct response?
How can I send data using the fetch method to php so that they end up in the $_POST variable.
In the javascript file I have the code:
async function post(url) {
let form = takeFormControl();
let test = {name: "test"};
let response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(test),
});
let result = await response.json();
console.log(result);
}
function takeFormControl(){
let form = document.querySelector(".form-control");
form.addEventListener("click", (e) => {
e.preventDefault();
});
return form;
}
if (isset($_POST['name'])){
echo json_encode(['status' => 'good', $_POST]);
}else{
echo json_encode(['status' => 'bad', $_POST, $_REQUEST]);
}
Answer the question
In order to leave comments, you need to log in
$_POST['name'] - this would be recognized if you sent the variable as form_data
You are sending just raw data
To see what you get as PHP input use
PS json_decode it won't work as it's not a valid json.
Valid json looks like this: {"name": "test"}
file_get_contents('php://input')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question