Home > Software engineering >  server side of Fetch API request doesn't receive data
server side of Fetch API request doesn't receive data

Time:07-25

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.

CodePudding user response:

Your fetch request is sending json to the server, the server is not expecting json, its expecting form data.
You can use a URLSearchParams object to send that type of data to your server.

 fetch('/api/apicreatebooking.php', {
      method: 'POST',
      body: new URLSearchParams ({        
            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
      })
  })

If you actually want to send JSON from the client side you have to change the way you read it on the server. The data is not stored in $_POST, you have to read it from stdin.

<?php
$a="a>";
$json = file_get_contents("php://input");
$data = json_decode($json, true);
if (isset($data['fromDate'])) {$a  = $data['fromDate'];}
if (isset($data['toDate'])) {$a  = $data['toDate'];}
if (isset($data['apptmnt'])) {$a  = $data['apptmnt'];}
if (isset($data['total'])) {$a  = $data['total'];}
if (isset($data['lan'])) {$a  = $data['lan'];}
$result = array(
    "success" => true,
    "message" => $a,
    "bookingCode" => '1234567'
);

$output = json_encode($result);
echo $output;

CodePudding user response:

There is a little issue with 2nd code snippet above from Musa.

It has to be $data = json_decode($json, true);

  • Related