Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use react-native with php with fetch return data is always null

My return is always null. i cant seems to get this to work. How can I use react-native with php with fetch json. anyone can help?

PHP

$myArray = array();
$myArray['lat'] = $_POST['lat']; 
$myArray['lng'] = $_POST['lng'];
echo $_POST['lat'];

React-Native Fetch

fetch(url, {
  method: 'post',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    lat: region.latitude,
    lng: region.longitude,
  }),
})
  .then((response) => response.json())
  .then((responseData) => {
    console.log(responseData);
  })
  .catch((error) => {
    console.warn(error);
  })
  .done();
like image 443
phongyewtong Avatar asked Sep 08 '15 03:09

phongyewtong


People also ask

Does react native support fetch?

React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.


1 Answers

Have to use file_get_contents('php://input') if not php cant see the data.

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

$myArray = array();
$myArray['lat'] = $json['lat']; 
$myArray['lng'] = $json['lng'];
$myArray['status'] = 'success';
echo json_encode($myArray);
like image 69
phongyewtong Avatar answered Sep 20 '22 13:09

phongyewtong