Stijn Bernards
Stijn Bernards

Reputation: 1091

Jquery each not continuing after ajax $.post

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

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

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

maddy
maddy

Reputation: 117

Use $.ajax() instead of $.post. As, it has got lot many configurable paramenters. Here you can use Promise pattern.

Upvotes: 0

aleha_84
aleha_84

Reputation: 8539

Take a look here and here. It is two different solutions.

It's just rewrite all your response. Try to store them in array, or use async: false, which make all your request work in queue.

Upvotes: 0

Related Questions