Hi
My issue is that I want to either call 2 AJAX functions one after the other OR call just the second one.
Let me put this into context.. I am writing a "store locator" application. By default all the results are loaded in alphabetical order. A user is able to enter their address or postcode into a box and hit search. My application will then find their latitude and longitude coordinates from their input using Google's geocoding API and then pass these coordinates into my own AJAX call which will then order the results based on their location, closest store first.
However, if the user does not enter a postcode I want to just go back to the default and show the results in alphabetical order once again.
So far...
function generateResults(_postcode) {
//console.log("generating results");
if (readyState) {
changeReadyState(false); // Changes the state of the application, lays a translucent DIV on top of the controls and only allows single execution of this function
jQuery.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + encodeURIComponent(_postcode) + ",UK&sensor=false",
success: function(d){
var _u = ajax_url;
if (d.results && d.results[0] && d.results[0].geometry && d.results[0].geometry.location) {
var location = d.results[0].geometry.location;
_u = appendQS(_u, "lat=" + location.lat); // Appends as query string, putting either ? or & before
_u = appendQS(_u, "lng=" + location.lat);
jQuery.ajax({
url: _u,
success: function(data){
changeReadyState(true);
},
error: function(){
changeReadyState(true);
},
async: false
});
}
else if (d.error_message) {
alert(d.error_message);
changeReadyState(true);
}
else {
alert("No results found for '" + _postcode + "'");
postcodeTxt.val("");
changeReadyState(true);
}
},
error: function(){
changeReadyState(true);
}
});
}
else {
//console.log("Application busy, try again soon");
}
}
I suppose I could just have two cases depending on whether the _postcode
is empty or not but this would mean repeating code.
Basically I want to only call the Google Geocoding API if the _postcode
field is not empty, but I want to ensure that this call is either not going ahead or has finished before I call my own AJAX.
I had a look at making the first request synchronous but according to the jQuery docs, it's been deprecated and they recommend using their success/error/complete callbacks instead.
I've a feeling it's just a bit late in the day!
Cheers