5

I'm having this problem, where for some reason I can't send data to another PHP script with POST over the fetch API.

I've already checked other solutions and cleaned up my code, but it still won't work.

Maybe I'm missing something.

Here's my code:

function request(where, num, last, query){
 for (var i = num; i > 0; i--) {
  fetch("global/modul.php", {
   method: "POST",
   body: JSON.stringify({
    last: last,
    query: query
   }),
   headers:{
    'Content-Type': 'application/json'
   }
  }).then(function (response) {
   return response.text();
  }).then(function (data) {
   let html = data.trim();
   document.getElementById(where).innerHTML += html.trim();
  }).catch(function (error) {
   console.log('Request failed', error);
  });

  last = document.getElementById(where).lastChild.id;
 }
}
    var_dump($_POST);

Prints:

array(0) { }

I've also tested the solutions shown in Parse Javascript fetch in PHP, but it didn't solve the problem. I still don't get the POST data in my php-script.

Rot-man
  • 18,045
  • 12
  • 118
  • 124
Morplson
  • 73
  • 1
  • 8

1 Answers1

13

There is no problem with your JS code. However you need to look for the data in another variable in your PHP code, by reading php://input like so:

$_POST = json_decode(file_get_contents('php://input'), true);

Source: https://stackoverflow.com/a/39508364/2831645

thibpat
  • 714
  • 5
  • 17