I'm experiencing a bug with my code when used on mobile devices (issue does not happen with the faster processing time of PCs). I suspect that the issue that I'm having is to do with functions not firing sequentially - ie they will still go ahead, even if all the parameters are not set.
The basic premise is that JQuery Geolocation is called, and the latitude/longitude data is used in conjunction with a parameter passed via an onClick function. This is then passed into AJAX that comes back with results based off this data.
During testing on mobile devices, however, sometimes when you click on links, the GPS won't fire in time, but it will still go ahead. The result is that nothing comes back and the user is faced with a blank screen. If you give it enough time and click enough, it will work. This doesn't always happen, but it appears that not all data is ready.
I've tried a number of variations, but as I'm only an intermediate JS coder, I can't work out where the problem lies. Love some feedback!
if(navigator.geolocation) {/* Function for returning list of locations for a unique cuisine */
function locationList(clicked_id) {
navigator.geolocation.getCurrentPosition(
function(position) {
$.ajax({
url: 'search.php',
type: 'GET',
data: 'id=' + clicked_id + '&action=geolocation&latitude=' + position.coords.latitude + '&longitude=' + position.coords.longitude,
beforeSend: function () {
$('#location-list').html('<div class="ajax-load"><img src="img/ajax-loader.gif" /></a>');
},
success: function (msg) {
$('#location-list').html(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
}, /* position */
function() {
$('#location-list').html('<div class="toolbar"><h1>GPS Error</h1><a class="back" href="#home">Home</a></div><div class="scroll"><ul class="rounded"><li><p>To take advantage of this app you need the GPS capability of your phone turned on. Please check whether this is turned on or else the app will not work</p></li></ul></div>');
} /* no position so failure */
);
} /* locationList */
}/* navigator.geolocation */
It's not so much the sequence of your custom functions (which typically WILL execute in a serial fashion), it's internal APIs; in this case, $.ajax
. By default, the Ajax call is asynchronous, so the rest of the function will move along, not caring about the response yet.
To wait for the response, add the parameter async: false
to your Ajax call.
[edit to add:] As per jfriend00's comment, this is going to lead to bad user experience. I had no intention of redesigning the OP's approach for him, but at the same time I don't want to imply endorsement when the design can be greatly improved by working WITH async.