I am sending data with a POST
request via Fetch, but it appears as if the data is not received on the server side. You will find what happens after the code.
CLIENT POST REQUEST
const formMobile = document.getElementById('quoteMobile');
if (formMobile) {
formMobile.addEventListener('submit', function(e){
e.preventDefault()
console.log("submit fired");
console.log(
document.getElementById('fromDate').value +
document.getElementById('toDate').value +
document.querySelector('input[name="unit"]:checked').value +
document.getElementById("total").value +
document.getElementById("lan").value
);
fetch('/api/apicreatebooking.php', {
method: 'POST',
body: JSON.stringify({
fromDate: document.getElementById('fromDate').value,
toDate: document.getElementById('toDate').value,
apptmnt: document.querySelector('input[name="unit"]:checked').value,
total: document.getElementById("total").value,
lan: document.getElementById("lan").value
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
}
})
.then(function(response){
return response.json()})
.then(function(data){
console.log(data)
body=document.getElementById("bodyDiv")
messages=document.getElementById("messagesDiv");
if (data.success) {
bookingCode = data.bookingCode;
phpFile = 'mbooking_form_content2.php'
$('#bodyDiv').load('/presentation/' + phpFile + '?bookingCode=' + bookingCode);
} else {
messages.innerHTML = data.message;
}
}).catch(error => console.error('Error:', error));
});
}
SERVER SIDE
<?php
$a="a>";
if (isset($_POST['fromDate'])) {$a += $_POST['fromDate'];}
if (isset($_POST['toDate'])) {$a += $_POST['toDate'];}
if (isset($_POST['apptmnt'])) {$a += $_POST['apptmnt'];}
if (isset($_POST['total'])) {$a += $_POST['total'];}
if (isset($_POST['lan'])) {$a += $_POST['lan'];}
$result = array(
"success" => true,
"message" => $a,
"bookingCode" => '1234567'
);
$output = json_encode($result);
echo $output;
From the 2nd client side console.log
, I see that all data is present. The server side also returns the $result
array, however, it looks like this (client side console.log
: {success: true, message: "a>", bookingCode: "1234567"}
. So none of the transmitted data has been received - or at least I cannot receive it with $_POST
.
For some strange reason I have found very little documentation of the server side of the Fetch API, but my understanding is it works like any POST request (if using POST for the request). I also found one answer where someone removed the content-type from the success and became lucky, didn't work here.