How to grab data using fetch() API POST method in PHP?

trupti picture trupti · Oct 30, 2015 · Viewed 27.8k times · Source

I am trying to use fetch() API POST method in order to grab the POST data in PHP.

Here is what I have tried:

var x = "hello";
fetch(url,{method:'post',body:x}).then(function(response){
    return response.json();
});

PHP:

<?php
if(isset($_GET['x']))
{
    $get = $_GET['x'];
    echo $get;
}
?>

Is this correct?

Answer

Salva picture Salva · Jan 8, 2016

It depends:

If you want to $_GET['x'], you need to send the data in the querystring:

var url = '/your/url?x=hello';

fetch(url)
.then(function (response) {
  return response.text();
})
.then(function (body) {
  console.log(body);
});

If you want to $_POST['x'], you need to send the data as FormData:

var url = '/your/url';
var formData = new FormData();
formData.append('x', 'hello');

fetch(url, { method: 'POST', body: formData })
.then(function (response) {
  return response.text();
})
.then(function (body) {
  console.log(body);
});