Search code examples
phpjsonreactjsreact-hooksfetch

Fetch JSON React to PHP


I created a button in React allowing me to store the data in a JSON by using Fetch and send it to a local PHP server as well.

I receive a call from my PHP file but I can't get the data.

Here is the React :

const handleSubmit = (e) => {
    e.preventDefault();
    const requestOptions = {
      method: 'POST',
      mode: 'no-cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: 'React POST Request Example' })
  };
  fetch('http://localhost:8000/index.php', requestOptions)
        .then(response => response.json())
        .then(data => this.setState({ postId: data.id }));

}; 

And here the PHP (I only try to print values) variables are always empty

header('Access-Control-Allow-Origin: *');


if ($_SERVER["REQUEST_METHOD"] == "POST") {
error_log(print_r($_REQUEST, true));
error_log(print_r($_SERVER, true));
error_log(print_r($_POST['title'], true));

$var = $POST['title'];
error_log(print_r($var, true));
return;

}


if ($_REQUEST) {
error_log(print_r("omg", true));
return;

}

if (isset($_POST)) {
    echo print_r($_POST,true);
    return 0;
}

I also have the following error in React when I send the data.

Uncaught (in promise) SyntaxError: Unexpected end of input at :54:23


Solution

  • Because you don't return any JSON as expected by response.json().

    You can get your incomming data using file_get_contents('php://input').

    // prepare data to return
    $dataToReturn = [];
    
    // populate the data as you need
    $dataToReturn = json_decode(file_get_contents('php://input'));
    
    // Output the JSON string with appropriate header
    header('Content-Type: application/json');
    echo json_encode($dataToReturn);
    exit(0);