Search code examples
javascriptphpajaxfetch-apijquery-ajax

How To Send Object Data With Fetch API


I want to send a object as data with Fetch API with keepalive to the current page and get the data through php.

Just like in jQuery, we send data in a form of object, like this :

$.ajax({
  type: 'POST',
  async: false,
  data: {
    name: 'Tommy',
    type: 'dog',
    age: 7,
  }
}); 

And receive it as a variable like this in PHP :

<?php
  echo $_POST['name'] . ' is a ' . $_POST['type'];
  // This returns "Tommy is a dog"
?>

How can I achieve this with Fetch API. I've searched everywhere but I can't find the right answer.

I've tried this but it is not working.

fetch('', {
    method: 'POST',
    body: {name: 'blabla'},
    keepalive: true
});

Solution

  • You could call fetch with json as content-type and use method POST as you allready tried, you also have to serialize the content on the body

     fetch("backend.php", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({ name: "blablabla" }),
    });