0

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.

w461
  • 2,168
  • 4
  • 14
  • 40

2 Answers2

1

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;
Musa
  • 96,336
  • 17
  • 118
  • 137
  • This sounds very convincing. I just implemented it but yet no change (done both sides). Tomorrow I will look into this in more detail to get it work with this new information – w461 Jul 23 '22 at 15:32
  • Did you try each side individually? Don't do both only do one – Musa Jul 23 '22 at 15:34
  • Sorry was in a rush yesterday and did not read carefully enough. In THEORY it works great now, in PRACTICE this is totally weird: `$a=print_r($data,true);` provides me `"stdClass Object( [fromDate] => 2022-07-09 [toDate] => 2022-07-16 ...` as response, however, as soon as I use `if (isset($data['toDate']))` or `$a += $data['apptmnt'];` (any value), I receive `Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:8888/api/apibooking.php` and `Error: SyntaxError: The string did not match the expected pattern.` in `.catch(error => ...` – w461 Jul 24 '22 at 07:28
  • I found the issue: It has to be `$data = json_decode($json, true);` – w461 Jul 24 '22 at 15:45
0

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

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

w461
  • 2,168
  • 4
  • 14
  • 40