7

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();

1 Answer 1

9

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

4 Comments

have happend with me too .. still trying to figure out why i had to use file_get_contents('php://input') when we use 'Content-Type': 'application/json' , do you have idea why this is happening ?
If I get it ill add answer here and let you know
Sure. Thanks alot! :)
The reason that you have to use file_get_contents('php://input') is because its not form data. It is passing in a raw body request there and so php doesn't know to parse that as JSON by default. You are passing in a JSON body and anytime you use something like that you will have to parse it that way.

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.