skip to Main Content

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

2

Answers


  1. 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));
    
    Login or Signup to reply.
  2. 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" }),
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search