17

I'm calling a post request through Javascript and here's how it looks,

function syncDeviceId(deviceID, mod){
  var request = new Request('url', {
    method: 'POST',
    body: JSON.stringify({
        uuid: unique_id,
    }),
    mode: 'cors'
  })

  fetch(request).then(function(data) {
    return
  })

And I'm trying to retreive the values like this,

<?php

$post['uuid'] = $_POST['uuid']; 

?>

This is returned as empty, how can I retrieve the values from the fetch post request in PHP. Thanks

rksh
  • 3,920
  • 10
  • 49
  • 68

3 Answers3

20

This is because you are not setting Request's body to the correct format.

https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#Parameters

body: Any body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that a request using the GET or HEAD method cannot have a body.

The content-type header is based on the object set to body, or to the Content-Type specified in a Header object if supplied.

So setting body to a JSON string makes the content-type header be text/plain. Even if you set the request Content-Type to application/json it wouldn't matter because PHP does not by default know how to parse incoming JSON request payloads (unless it was recently added in PHP 7).

You can do a couple things client side

Create a FormData object from your object, and use that as body, and a multipart/form content-type will be used

var data = {some:"data",even:"more"};
var fd = new FormData();
//very simply, doesn't handle complete objects
for(var i in data){
   fd.append(i,data[i]);
}
var req = new Request("url",{
   method:"POST",
   body:fd,
   mode:"cors"
});

Create a URLSearchParams object which will set the content-type to application/x-www-form-urlencoded. Note: URLSearchParams is not widely supported

//Similar to creating a simple FormData object
var data = {some:"data",even:"more"};
var params = new URLSearchParams();
for(i in data){
   params.append(i,data[i]);
}
var req = new Request("url",{
   method:"POST",
   body:params,
   mode:"cors"
});

Create a query string (ie a=hello&b=world) and use a Headers object to set Content-Type to application/x-form-urlencoded

var data = {some:"data",even:"more"};
var headers = new Headers({
    "Content-Type":"application/x-form-urlencoded"
});
var params = [];
for(i in data){
   params.push(i + "=" + encodeURIComponent(data[i]));
}
var req = new Request("url",{
   method:"POST",
   body:params.join("&"),
   headers:headers,
   mode:"cors"
});

If you still want to send a JSON payload instead of doing the above you can, but you will have to read the raw request input and then use json_decode to get to the data

$json = file_get_contents('php://input');
$data = json_decode($json);
scraaappy
  • 2,830
  • 2
  • 19
  • 29
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
4

I too was having the same issue.

I used Chrome debug tool first to make sure that I was passing on a Request Body (Which the chrome debug will call "Request Payload") I was sending

{ClientDomain: "example.com"}

I then used the stated code in my receiving PHP script.

$json = file_get_contents('php://input');
$data = json_decode($json);

which then put my JSON code into an array which I could then read in PHP.

PRINT $data["ClientDomain"];

I hope this helps the next guy.

CMATION
  • 41
  • 1
-1

You need to echo your result, so it will be returned in the body of your request:

<?php

$post['uuid'] = $_POST['uuid']; 
echo $post['uuid'];
?>

Additionally, it looks like you need to instantiate your request object with the url of the php script you're calling:

var request = new Request('my_script.php', { . . .

Wherever your php script is.

eggmatters
  • 1,130
  • 12
  • 28
  • 1
    Well I used print_r and the result was Array ( [uuid] => ) – rksh Jan 29 '16 at 18:50
  • 1
    If it's your code above, your's passing your request to 'url'. That needs to be the php script you're actually calling. I will ammend my answer for this. – eggmatters Jan 29 '16 at 18:52
  • It is a php script I just removed the real url and replaced it with 'url' – rksh Jan 29 '16 at 18:54
  • I'm assuming you replaced it for the purposes of posting this question. Since, you're echoing results, let's just assume you're getting a 200 response. What is the output of `print_r($_POST)`? What is the structure of your `data` argument in the promise callback? – eggmatters Jan 29 '16 at 19:01