18

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

2
  • 1
    There's nothing wrong with your PHP code. What does the actual network request look like in your browser's debug tools? Commented Jan 29, 2016 at 18:45
  • What have you tried to debug the problem? Have you checked the request going out properly? Commented Feb 15, 2020 at 22:03

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

The very last method you mentioned always returns an empty string for me.
@LonnieBest, If file_get_contents('php://input') is returning an empty string then your POST request didn't send a request body
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.

Comments

-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.

4 Comments

Well I used print_r and the result was Array ( [uuid] => )
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.
It is a php script I just removed the real url and replaced it with 'url'
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?

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.