Skip to content Skip to sidebar Skip to footer

Sending Data To PHP Server With Fetch API (POST Method And JSON Preferred)

I'm trying Fetch API for the first time and I have problems sending POST data to a PHP server. I'm moving away from $.ajax and trying pure javascript solutions to communicate with

Solution 1:

There is two ways to use Fetch API: one>

let response = await fetch(url,[Options]);

if (response.ok) { // if HTTP-status is 200-299
  // get the response body (the method explained below)
  let json = await response.json();
} else {
  alert("HTTP-Error: " + response.status);
}

and the second way is to use pure promise syntax:

fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
  .then(response => response.json())
  .then(commits => alert(commits[0].author.login));

now lets talk about options and data: your data must be a JavaScript object like this:

      let data = {
        test: "toast",
      };

then you can config your headers like this:

let headers: {
       "Content-Type": "application/json"
      }
  };

finally use fetch like this:

let response = await fetch(url, {
        method: "POST",
        headers:headers,
        body: JSON.stringify(data)
      });

I think your problem is using FormData instead of stringified JavaScript object


Post a Comment for "Sending Data To PHP Server With Fetch API (POST Method And JSON Preferred)"