I'm trying to write a script that pass geolocation's lat and lng as an array to PHP and return a value to the client side by using jQuery AJAX. The best solution that i could find was JSON. My following scripts return me NULL value for some reason that i couldn't tell.
index.html
<div id="geoloc"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$('#geoloc').html("<p>Geolocation is not supported by this browser</p>");
}
function showPosition(position) {
var latlng = [ {"lat":position.coords.latitude, "lng":position.coords.longitude}];
$.ajax({
type: "POST",
url: "libs/filterstores.php",
data: { json: JSON.stringify(latlng) },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
}
});
}
});
</script>
filterstores.php
$currloc = json_decode($_POST['latlng'], true);
$stores = array('lat'=>$currloc['lat'],'lng'=>$currloc['lng']);
echo json_encode($stores);
The following will be results what i got in returns once i hit the "share location" button pop up from the browser
Latitude: sdf
Longitude: sdfsd
console.logthings to see if your code is actually run. Then add that debugging info here= (in the question, not in a comment!)$_POST['currloc']and$currlocafterjson_decode.datatype: "json", JQuery will automatically JSON encode thedatayou give. No need to do it on your own.