Reputation: 1091
My jQuery each seems to be stopping until the ajax request has loaded. What is the problem here I thought ajax was async?
code:
$('div').each(function(){
if($(this).attr('id')){
var that = this;
$.post('application/views/dashboard/dashboard.php?component='+$(this).attr('id')+"&settingid="+settingId, function(response){
$(that).html(response);
$(window).trigger('resize');
});
settingId++;
}
});
Upvotes: 1
Views: 334
Reputation: 93581
$.when
will wait on all async calls to complete (order and timing unimportant), then can perform a single extra operation at the end (in addition to the individual operations). You will need to use $.ajax
instead of the simpler $.post
:
var requests = [];
$('div').each(function () {
if ($(this).attr('id')) {
var that = this;
requests.push($.ajax({
url: 'application/views/dashboard/dashboard.php?component=' + $(this).attr('id') + "&settingid=" + settingId,
type: "post",
success: function (response) {
$(that).html(response);
}
}));
});
settingId++;
});
$when(requests).then(function () {
$(window).trigger('resize');
});
$.when
works by taking an array of jQuery promises (in this case ajax promises) and awaiting a success from them all.
apologies for any typos in the above code. I just wrote is direct into the answer :)
You can of course simplfy the code from this:
$('div').each(function () {
if ($(this).attr('id')) {
to this:
$('div[id]').each(function () {
Upvotes: 1
Reputation: 117
Use $.ajax() instead of $.post. As, it has got lot many configurable paramenters. Here you can use Promise pattern.
Upvotes: 0