You are somewhat close, but you should put your function inside the document.ready
event handler instead of the other-way-around.
Another way to do this is by placing your AJAX call in a generic function and call that function from an AJAX callback to loop through a set of requests in order:
$(function () {
//setup an array of AJAX options,
//each object will specify information for a single AJAX request
var ajaxes = [
{
url : '<url>',
data : {...},
callback : function (data) { /*do work on data*/ }
},
{
url : '<url2>',
data : {...},
callback : function (data) { /*maybe something different (maybe not)*/ }
}
],
current = 0;
//declare your function to run AJAX requests
function do_ajax() {
//check to make sure there are more requests to make
if (current < ajaxes.length) {
//make the AJAX request with the given info from the array of objects
$.ajax({
url : ajaxes[current].url,
data : ajaxes[current].data,
success : function (serverResponse) {
//once a successful response has been received,
//no HTTP error or timeout reached,
//run the callback for this request
ajaxes[current].callback(serverResponse);
},
complete : function () {
//increment the `current` counter
//and recursively call our do_ajax() function again.
current++;
do_ajax();
//note that the "success" callback will fire
//before the "complete" callback
}
});
}
}
//run the AJAX function for the first time once `document.ready` fires
do_ajax();
});
In this example, the recursive call to run the next AJAX request is being set as the complete
callback so that it runs regardless of the status of the current response. Meaning that if the request times out or returns an HTTP error (or invalid response), the next request will still run. If you require subsequent requests to only run when a request is successful, then using the success
callback to make your recursive call would likely be best.
Updated 2018-08-21 in regards to good points in comments.