Getting trouble sending users geolocation through AJAX into a php file.
Here the code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
$.ajax({
type: 'POST',
data: pos,
url: '/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
Have tried diferent ways to write data like:
data: {pos}
,
data:({pos})
,
data: {lat: position.coords.latitude, lng: position.coords.longitude},
And that it's the error that I get in template-userslocation.php
:
Notice: Undefined index: pos in /home/.../template-userslocation.php on line 7
SOLVED:
The problem was that I've been working in Wordpress and it has it own way to handle with javascript:
pos
is the name of the variable, from PHP it will not know that, it will only see $_POST['lat']
and $_POST['lng']
So use:
$.ajax({
type: 'POST',
data: {'pos': pos},
url: '/wp-content/themes/atripby/template-userslocation.php'
});
Then from PHP access like:
$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;