8

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 different servers (sometimes local, sometimes not). Now I'm trying to understand Fetch API and, even if it's simple and intuitive, I've stumbled on a weird and unexpected problem:

  • I CAN'T send JSON post to PHP server

  • I CAN send form-data post to LOCAL PHP

  • I CAN'T send form-data post to WEB URL PHP

I can (obviously) retrieve data from all the above, but strangely nothing arrives. Through $_SERVER['REQUEST_METHOD'] I can see that when using the LOCAL path I get "POST" as I asked, but when using the WEB URL it changes in GET for some reason I don't understand.

url="/";
url="www.something.com";
fetch(url, {
    method: 'POST',
    body: JSON.stringify({
        test: "toast",
    })
})
.then(function(response) {
    return response.text();
})
.then(function(data) {
    console.log(data);
});

I expect just to send and receive data in a solid and clear way. No jquery, no libraries, etc. I just want to send a JSON {"test":"toast"} and find it on the PHP file when checking the $_POST var.

UPDATE

It seems that the problem with local and web urls were on this difference: www.something.com/test => www.something.com/test/index.php. Without index.php for some reason it refused the POST data (but read the echoed info anyway). But the problem about JSON remain.

  • I CAN'T send JSON post to PHP

  • I CAN send form-data post to PHP

UPDATE

I found that $_POST and $_GET don't work well with Fetch API. You have to use php://input to get all the data sent to the server.

Don't know why. There's a better solution? Why ajax and XMLHttpRequest don't have this kind of problems?

Note: If you want the data to be recognized as json, you have to specify it with a header, even this was never requested so why now? Is Fetch API missing something?

header('Content-Type: application/json');

$test=json_decode(file_get_contents("php://input"));
//some code
echo json_encode($test);
4
  • I am not sure. But I tried your code and it worked very well for me. May be you can recheck the URL to which you are trying to send the data to. Commented Oct 19, 2019 at 13:40
  • Did you tryed with JSON? I just updated now Commented Oct 19, 2019 at 14:42
  • is this still the case, that php doesnt work well with the fetch api? Commented Jan 14, 2024 at 9:45
  • This question is similar to: How to grab data using fetch() API POST method in PHP?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 13, 2024 at 2:08

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, great explanation! But unfortunately it has the same problems of my previous attempts... I searched on many articles and I fail to find why I get this kind of problems :( About FormData and JSON, I found that on php for some reason, with Fetch API, it's the only way. And it works! (like on your example) But only locally...
UPDATE: It seems that the problem with web urls were on this difference: [link](www.something.com/test) => [link](www.something.com/test/index.php). Without index.php for some reason it refused the POST data (but read the echoed info anyway). But the problem about JSON remain.
@Andrea I found a soluction with formData and mode: 'no-cors' in the fetch settings. Check this answer
2

I hope someone will find this answer. I am using Codeigniter 3.1.11 and I've found the answers after getting help from a friend.

Controller

class YourController extends CI_Controller
{
    public function yourMethod() {

        // THIS CODE IS A MUST!
        $input = json_decode(file_get_contents('php://input'), true);

        // You get the data you sent via FETCH
        var_dump($this->input->post('testdata'));
    }
}

FETCH POST JAVASCRIPT

let postData = new FormData();
postData.append('testdata', 123);
                            
fetch('http://localhost/your-app-name/yourcontroller/yourMethod', {
    method: 'POST',
    mode: 'no-cors',
    headers: {
        "Content-Type": "application/json"
    },
    body: postData
}).then((res) => {
    console.log(res);
    }).catch(console.log);

To view the preview of the data you send or get using Fetch you can inspect, go to tab Network, in the table "Name", click yourMethod then go to tab "Preview". In the preview you can see 123.

2 Comments

Was this tested on a server as well, or just locally?
This is incorrect, as you should either be using FormData or JSON, not both.
0

See this example on github

In brief

*.js

fetch("post.php", {
method: "post",
mode: "cors",
headers: {
  "Content-Type": "application/json"
},
body: {myData: "hello world"}
})

*.php

$data = json_decode(trim(file_get_contents("php://input")));
echo $data["myData"] // prints hello world!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.