1

I am currently working on a React Native app that is trying to send JSON data to a server through PHP. All it is doing is showing me an empty string and I cannot figure out why. It also showed me an empty array when I tried to do something similar in Android Studio. Here is my React Native code (this app gets latitude and longitude using Geolocation and sends it to a server every 10 seconds for another app to grab from the server and do something with).

In this function, I attempt to do a POST request to the server:

sendDataToServer = () => {
var data = {
  "lat": this.state.where.latitude,
  "long": this.state.where.longitude
}

fetch('http://....sendData.php', {
  method: 'POST',
  headers: {
    'Accept' : 'application/json',
    'Content-Type' : 'application/json',
  },
  body: JSON.stringify(data)
}).then((response) => {
  return response.json()                            
  })
      .then((responseData) => {

      }).catch((error) => {
        console.error(error);
      });
}

This is the function I call sendDataToServer() from:

geoSuccess = (position) => {
this.setState({
  ready:true,
  where: {latitude: position.coords.latitude, 
          longitude: position.coords.longitude}
});
this.setState({
  TextLat:
    this.state.where.latitude + " ",
  TextLong:
    this.state.where.longitude + " "
});
this.sendDataToServer();
}

And here is my PHP:

<?php
    $json = file_get_contents('php://input');
    echo json_encode($json);

All it gives me is "" in my PHP when I run it. I don't know if it's the json_encode or how I'm receiving the data or what. When I try to use echo json_last_error_msg() after json_encode, it echos "No error" in my PHP file, and my React Native app gives me an error saying "SyntaxError: JSON Parse error: Unable to parse JSON string". Any help is greatly appreciated!

4
  • 1
    Hi Olivia, could you please show the contents of php://input? Commented May 3, 2020 at 23:30
  • How can I see the contents of php://input? Commented May 3, 2020 at 23:36
  • You can use var_dump( file_get_contents('php://input')); to learn more about php://input. Could this question help you? Commented May 3, 2020 at 23:39
  • 1
    Using that, I get string(0), so there must be issues with the data I am sending? Commented May 3, 2020 at 23:49

0

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.