Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP couldn't get $_POST data from Js FormData fetch?

I want to send JSON data (in this case is client timestamp) to my server. However, my code seem doesn't work as I expect.

My idea is using fetch to send FormData (which contain an input has JSON as value) to the PHP. At the server side, PHP will take care the form with $_POST and return JSON string to me.

I'm using a free host service, which has PHP 7.0, for testing stuff.

All of the code below is in the same file (404.php):

var now = new Date();

var pkg = JSON.stringify({
    ts: now.getTime(),
    tz: now.getTimezoneOffset() / -60
})

var form = new FormData();
form.set('json', pkg);

console.log(form.has('json')) // true
console.log(form.values().next()) // return and obj contain JSON string

fetch('/404.php', {
    method: 'POST',
    body: form
});
$json = null;
if(isset($_POST['json'])) $json = json_decode($_POST['json']);

var_dump($_POST); //Result: array(0) { }

As you can see, the output of var_dump is an empty array. But what I expect to see is an output with a JSON string.

I've tried another way, which is this one fetch-api-json-php, but it also no use. All the resource I found on the Internet usually about the classic AJAX, not fetch API. And most of them are only for client side, there isn't much I could find for PHP/server side.


1 Answers

Can you try to run this code in your local machine?

Make a file name 55788817.php and paste this code and run.

  <?php
  if (isset($_POST) && !empty($_POST)) {
    $json = null;
    if(isset($_POST['json'])) $json = json_decode($_POST['json']);

    var_dump($_POST); //Result: array(1) { ["json"]=> string(29) "{"ts":1555915560755,"tz":5.5}" }
    exit;
  }
  ?>
  <!DOCTYPE html>
  <html>
  <head>
    <title></title>
  </head>
  <body>
    <button type="button" id="registerButton">Click Me!</button>
    <script>
      var now = new Date();

      var pkg = JSON.stringify({
          ts: now.getTime(),
          tz: now.getTimezoneOffset() / -60
      })

      var form = new FormData();
      form.append('json', pkg);

      console.log(form.has('json')) // true
      console.log(form.values().next()) // return and obj contain JSON string
      fetch('./55788817.php', {
          method: 'POST',
          body: form
      });
    </script>
  </body>
  </html>
like image 133
Vasant Hun Avatar answered Jun 25 '26 21:06

Vasant Hun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!