How To Send Object Data With Fetch API

1.1k Views Asked by At

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
});
2

There are 2 best solutions below

0
Trond On BEST ANSWER

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" }),
});
0
Emilien On

No idea what keepalive is, but if I want to send a fetch request to a php backend I would usually do something like this:

        fetch("backend.php", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
          },
          body: "data=" + data,
        })
          .then((response) => response.json())
          .then((response) => doWhatYouWant(response))
          .catch((error) => alert("Error : " + error));