/    Sign up×
Community /Pin to ProfileBookmark

JS POST using fetch to PHP

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′>=&gt;</font> <small>float</small> <font color=’#f57900′>-36.7755264</font>
<i>public</i> ‘lon’ <font color=’#888a85′>=&gt;</font> <small>float</small> <font color=’#f57900′>174.7124224</font>
</pre>

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMay 10.2020 — Looks fine so far: lat and lon are available in data. What's the issue?
Copy linkTweet thisAlerts:
@kiwisauthorMay 10.2020 — my console log shows raw HTML not a true array
Copy linkTweet thisAlerts:
@SempervivumMay 10.2020 — I know, var_dump() creates HTML in order to show the value(s) in a structured way. However the variables inside data are accessible:

`$lat = $data-&gt;lat;`

will assign the latitude to the PHP variable $lat;
Copy linkTweet thisAlerts:
@VITSUSAMay 11.2020 — @kiwis80#1618278 Can you please share the snapshot of the error?
Copy linkTweet thisAlerts:
@NogDogMay 11.2020 — Or just do something like this, if your goal is simply to inspect what's there?
<i>
</i>&lt;?php

$json = file_get_contents('php://input');
header('Content-Type: application/json');
echo $json;
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...