Smudger
Smudger

Reputation: 10809

jquery loop with ajax request works perfectly with an alert included, without alert fails?

I have the below syntax which works 100% correctly and populates the corresponding checkboxes:

for (var i = 1; i < 30; i++) {     
$.post('get_sku_prices', {data: $('#product'+i).val()},function(result) {
    $('#price'+i).val(result);
    $('#adjustedprice'+i).val(result);
});
alert(i);
}

As mentioned working correctly. If I remove the alert and just have

for (var i = 1; i < 30; i++) {   
$.post('get_sku_prices', {data: $('#product'+i).val()},function(result) {
    $('#price'+i).val(result);
    $('#adjustedprice'+i).val(result);
});

}

The fields are not being populated without the alert, almost like the alert is forcing the page to refresh.

Any ideas? Thanks in advance...

Upvotes: 0

Views: 229

Answers (4)

techfoobar
techfoobar

Reputation: 66693

That's because in the first case the alert() is blocking and needs to be dismissed for the loop to continue.

In the second case (without alert), the ajax calls get executed immediately without waiting for the responses. i.e when the response for the first request (i=1) arrives, i is not necessarily 1.

You can fix it by using $.ajax and its context option.

For example:

for (var i = 1; i < 30; i++) {     
    $.ajax({
        type: 'POST',
        url: 'get_sku_prices',
        data: {data: $('#product'+i).val()},
        context: {index: i}, // this value will be available in success as "this"
        success: function(result) {
            $('#price'+this.index).val(result); // use "this.index" here
            $('#adjustedprice'+this.index).val(result);
        }
    });
}

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

You can create your own scoping function, something like that:

for (var i = 1; i < 30; i++) {
    (function (index) {
        $.post('get_sku_prices', {
            data: $('#product' + index).val()
        }, function (result) {
            $('#price' + index).val(result);
            $('#adjustedprice' + index).val(result);
        });
    })(i)
}

Upvotes: 1

vijay
vijay

Reputation: 1353

Try adding some delay in function execution

var i=0;
function postRequest(i){
$.post('get_sku_prices', {data: $('#product'+i).val()},function(result) {
    $('#price'+i).val(result);
    $('#adjustedprice'+i).val(result);
});
setTimeout(function(){
    postRequest(i++);
},1000);
}

Upvotes: 0

panther
panther

Reputation: 79

Send Count to the server and try getting the count back on your result and do changes according to the count received from the result rather than the count from the for loop.

Upvotes: 0

Related Questions