Codemaster United
Codemaster United

Reputation: 381

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

Upvotes: 0

Views: 1651

Answers (2)

Trond
Trond

Reputation: 96

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

Upvotes: 1

Emilien
Emilien

Reputation: 629

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

Upvotes: 0

Related Questions