Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Javascript fetch in PHP

Tags:

javascript

php

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

like image 385
rksh Avatar asked Jan 29 '16 18:01

rksh


2 Answers

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);
like image 92
Patrick Evans Avatar answered Nov 05 '22 01:11

Patrick Evans


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.

like image 4
CMATION Avatar answered Nov 05 '22 01:11

CMATION