Quote of the day

About Me

Wednesday, February 20, 2013

Ajax call inside for loop issue and solution


Hello people, This post is regarding real day to day issue in coding and its resolution, It sometimes looks small issue but when it starts eating your time you start getting feeling that its no more smaller one, Here goes the issue

As the title of the blog suggests, When you are making AJAX calls inside loop, It is finitely possible that inside loop when the call is made, It takes time to get the result back to client side and by that time loop has already ended and counter has reached to limit and you end up thinking how to keep track of the request, it should get the correct index in "Success" method of $.ajax call, Otherwise it will keep on giving you one count higher than your total count of loop, There can be many way as we know in our world but below is one of the good solution to it

Solutions
See below code for an example

for (var i = 0; i < groupCount.length; i++) 
{
                !function (i) {
                    $.ajax({
                        type: 'POST',
                        url: ,
                        data: data,
                        dataType: "json",
                        success: function (respons) {
                            // Do some action
                            
                        },
                        error: function (err, para1, parra2) {
                           // Do some action 
                        }
                    });
                } (i);

Here we can see we have wrapped the ajax call into !function(), It will make sure that your ajax call works, no matter what !!!, One more dirty fix is that we can change the property called async=false in $.ajax parameters but that does not serve the purpose as when we use ajax it has to be async.

Small but helpful !!!

2 comments:

  1. this does not work every time..results are sporadic....i had 2 ajax calls inside of for and and only one runs....and ofcourse...sometimes both.

    ReplyDelete
    Replies
    1. If there are two ajax calls you need to tweak them, so just like one call you need to change the function for two calls

      Delete