1

I fetch data to server, and I want to see in the console params, which i send. But on PHP side $_POST value is empty and I always recieve empty array.(WEB -> PHP -> WEB) What I do wrong ?

JS code:

function json(response){
  return response.json()
}

let data = {obj : 'value'};

fetch('http://localhost/Fetch_mysql_angular/requests.php', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    "Content-type": "application/json"
  },
  body: JSON.stringify(data)
})
.then(json)
.then(function (data) {
  console.log(data);
})
.catch(function (error) {
  console.log('Request failed', error);
});

PHP code:

<?php

  echo json_encode($_POST);

?>

Console

[]

Thanks for spending time on my post!

Alex Movchan
  • 121
  • 1
  • 7

2 Answers2

1

When you using JSON.stringify(data) your data will be encoded and sent in json format and not form-data. So php will not fill $_POST variable.

You can still get POST json data by reading php://input

$data = json_decode( file_get_contents('php://input') ) ;
var_dump( $data );
Daniel
  • 78
  • 4
0

You're not returning the response in your callback.

function json(response){
  return response.json();
}
Josh
  • 1,455
  • 19
  • 33