How to call second jQuery.ajax instance on success of first and update page
Ajax calls are (by default) asynchronous. That means that this code:
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
could be executed before the ajax call preceding it is finished. This is a common problem for programmers who are new to ajax and asynchronous code execution. Anything you want to be executed after the ajax call is done must be put into a callback, such as your success
handler:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
Likewise, you could put the second ajax call in there as well:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
$.ajax({
url: "_js/loaddeals_v2.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
}
});
With jQuery 1.5's Deferred Object, you can make this slicker.
function firstAjax() {
return $.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
}
// you can simplify this second call and just use $.get()
function secondAjax() {
return $.get("_js/loaddata.php", function(results){
$('#listresults').html(results);
});
}
// do the actual ajax calls
firstAjax().success(secondAjax);
This is nice because it lets you un-nest callbacks - you can write code that executes asynchronously, but is written like synchronously-executed code.