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!