Home > Software engineering >  How To Send A Data Object With Fetch API
How To Send A Data Object With Fetch API

Time:12-05

I want to send a data object with fetch api with keepalive to the current page and get the data through php. how can I do it.

Data To Send

{
  name: 'blabla',
  age: 432,
  type: 'pig'
}

I want to recieve as a post variable

$_POST['name'];

I've tried this but it is not working

fetch('', {

            method: 'POST',

            body: {name: 'blabla'},

            keepalive: true

        });

Sorry for no code

CodePudding user response:

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

CodePudding user response:

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