I am in mobile app and I use multiple Ajax calls to receive data from web server like below
function get_json() {
$(document).ready(function() {
$.ajax({
url: 'http://www.xxxxxxxxxxxxx',
data: {
name: 'xxxxxx'
},
dataType: 'jsonp',
//jsonp: 'callback',
//jsonpCallback: 'jsonpCallback',
success: function(data) {
$.each(data.posts, function(i, post) {
$.mobile.notesdb.transaction(function(t) {
t.executeSql('INSERT into bill (barcode, buildingcode, buildingaddress, flatname, flatdescription, entryseason, period, amount, pastpayments, todaypayments, paydate, receiptno) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);', [post.Id, post.Code, post.Address, post.Name, post.Description, post.EntrySeason, post.Period, post.Revenue, post.PastPayments, post.todaypayments, post.paydate, post.receiptno],
//$.mobile.changePage('#page3', 'slide', false, true),
null);
});
$('#mycontent').append(post.Name);
});
}
});
$.ajax({
xxxx
});
$.ajax({
xxxx
});
});
}
How can I force the 2nd ajax call to begin after the end of the first... the 3rd after the end of the 2nd and so go on?
Haven't tried it yet but this is the best way I can think of if there umpteen number of ajax calls.
Method1:
If there are only a handful you can always nest them like this.
Method2:
Note: If it is repetitive task go for method1, And if each data is to be treated differently, nesting in method2 makes more sense.
Place them inside of the
success:
of the one it relies on.You could also use jquery when and then functions. for example
https://api.jquery.com/jQuery.when/
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:
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 thesuccess
callback to make your recursive call would likely be best.Updated 2018-08-21 in regards to good points in comments.
This is the most elegant solution I've been using for a while. It doesn't require external counter variable and it provides nice degree of encapsulation.