Problem is I need to wait for all ajax requests to be done before i execute the next line of code. This can be handled in 2 ways
1) Make the Ajax request synchronous
2) Implement of $.when() in jQuery and handle the next lines in callbacks (success/failure)
To make the Ajax call synchronous
jQuery.ajax({ async: false,....});
It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.
That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:
$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
}
If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.
In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.