Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_POST not retrieving data from Javascript's Fetch()

I'm posting data using javascript's fetch() .

    fetch('/string.php', {
      method: 'post',
      body: JSON.stringify({
        name: 'helloe world',
      })
    })
    .then(function(response) {
      if (response.status >= 200 && response.status < 300) {
        return response.text()
      }
      throw new Error(response.statusText)
    })
    .then(function(response) {
      console.log(response);
    })

string.php file contains:

print_r($_POST);

Now my problem is the $_POST returns an empty array. I can fix this by appending the file with:

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

But that feels very hackish and isn't ideal. Is this the intended behaviour for PHP when retrieving post data from a JS fetch()?

Is there anyway I may automatically put the contents within the $_POST?

like image 716
ditto Avatar asked Apr 16 '16 21:04

ditto


People also ask

Does fetch work with post?

A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.

How do I get fetch data?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

What is fetch () in JavaScript?

The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise. Syntax: fetch('url') //api for the get request .

How to use the JavaScript fetch API to get data?

How To Use the JavaScript Fetch API to Get Data Step 1 — Getting Started with Fetch API Syntax. The fetch () method returns a promise. If the promise returned is... Step 2 — Using Fetch to get Data from an API. The following code samples will be based on the Random User API. Using the... Step 3 — ...

What happens if the API you call using FETCH is down?

The API you call using fetch () may be down or other errors may occur. If this happens, the reject promise will be returned. The catch method is used to handle reject. The code within catch () will be executed if an error occurs when calling the API of your choice. To summarize, using the Fetch API will look like this:

What is the difference between fetch () and catch () methods in JavaScript?

The fetch () method returns a promise. If the promise returned is resolve, the function within the then () method is executed. That function contains the code for handling the data received from the API. Below the then () method, include the catch () method: The API you call using fetch () may be down or other errors may occur.

How to get data from API in JavaScript?

Define a constant data and store the data in JSON form by await response.json () method. Now we got the data from API by fetch () method in data variable. Pass this data variable to function which will show the data fetched.


2 Answers

$_POST is only populated by application/x-www-form-urlencoded or multipart/form-data requests.

For any other data format, you will need to parse php://input manually. In your case, you're using json_decode and putting the result in the $_POST superglobal, which is an acceptable way to "convert" from JSON to form data.

like image 191
Niet the Dark Absol Avatar answered Oct 19 '22 02:10

Niet the Dark Absol


But that feels very hackish and isn't ideal.

Assigning to $_POST is a bit weird. It is generally treated as read only. Most people would use another variable.

You should set the Content-Type on the request though, fetch will default to claiming a string is plain text unless you tell it otherwise.

Is this the intended behaviour for PHP when retrieving post data from a JS fetch()?

No. It is the intended behaviour when PHP doesn't support the content-type of the request body.

Is there anyway I may automatically put the contents within the $_POST?

Send form encoded or multipart data instead of JSON encoded data.

like image 22
Quentin Avatar answered Oct 19 '22 02:10

Quentin