I’m trying to use fetch to post data (not from a form) to another page on my server where I inset it into a database using PHP.
Here’s what I have
“`
navigator.geolocation.getCurrentPosition(position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(lat);
console.log(lon);
const data = {lat, lon};
fetch(‘enter.php’, {
method: ‘POST’,
body: JSON.stringify(data),
headers: {
‘Content-Type’: ‘application/json’
}
}).then(function (response){
return response.text();
}).then(function (text){
console.log(text);
}).catch(function(error){
console.error(‘error ‘ + error)
})
}
In php I have this
“`
<?php
$json = file_get_contents(‘php://input’);
$data = json_decode($json);
var_dump($data);
My log shows this
<pre class=’xdebug-var-dump’ dir=’ltr’>
<small>C:wamp64wwwtestingenter.php:7:</small>
<b>object</b>(<i>stdClass</i>)[<i>1</i>]
<i>public</i> ‘lat’ <font color=’#888a85′>=></font> <small>float</small> <font color=’#f57900′>-36.7755264</font>
<i>public</i> ‘lon’ <font color=’#888a85′>=></font> <small>float</small> <font color=’#f57900′>174.7124224</font>
</pre>