I have coded this function to detect and update postLat and postLon variables.
function searchAddSubmit(){
var shopId = 1; //random number to test the function
var postLon, postLat;
var shopTime = $("#selected-search-result-minutes").val();
navigator.geolocation.getCurrentPosition(function(position){
postLat=position.coords.latitude;
postLon=position.coords.longitude;
console.log(postLat);
console.log(postLon);
console.log('reun');
},function(error){});
console.log(postLat+" 1231");
console.log(postLon+" 1231");
$.ajax({
type: "POST",
url: "search-add-process.php",
cache: false,
dataType: "json",
data:{
id: shopId,
time: shopTime, //this value is taken from a form input
lat: postLat,
lon: postLon
},
success: function (data) {
if(data.error === true) {
alert(data.msg);
} else {
alert(data.msg);
//remove output when successful
}
}
});
}
I used Chrome’s Javascript Console tool to examine the variables (as printed with console.log()) and this is the result:
undefined 1231
undefined 1235
1.2957797
103.8501069
ruen
Coming to this point, I have these questions:
- Why are the variables
postLonandpostLatare not updated? In fact, the undefined variables are passed over tosearch-add-process.phpin the ajax block, not the actual values. - Why
navigator.geolocation.getCurrentPosition()function runs after theconsole.log(postLat+" 1231")line? Correct me if I am wrong, I always assumed that Javascript would execute line by line.
You first tell the Geolocation API to try to find the current position of the user, and you let it go and search while you do the rest of your work. This is called Asynchronous Execution. In other words, you let the Geolocation API take its time to search and find the place of the user, while you do the rest of your job (rest of your code is getting executed). Then when the API found the position, it executes the function you’ve passed to it.
Take the code of ajax into the success callback and everything would be fine.