0

I want to solve once for all the problem of looping ajax request and passing 'index' into it (the problem below):

for (var index = 0; index < 4; index++) {
    $.ajax({
        url: 'http://graph.facebook.com/',
        dataType: 'jsonp',
        success: function(json) {
            console.log(json[index]);
        }
    });
}

in this code within every 'success' callback 'index' will be 3. But I want to invoke callback with 0, 1, 2, 3. Many people are placing ajax request within a closure:

for (var index = 0; index < 4; index++) {
    (function(index){$.ajax({
        url: 'http://graph.facebook.com/',
        dataType: 'jsonp',
        success: function(json) {
            console.log(json[index]);
        }
    });
    })(index);
}

what in my opinion is a huge mistake - what if the request won't be there at the time? Than 'json' variable will be 'undefined'.

Does any of You guys have some proper way to solve this issue?

6
  • This is what you need api.jquery.com/category/deferred-object Commented Dec 17, 2013 at 8:09
  • I dont get why you think closure is a bad solution here. Commented Dec 17, 2013 at 8:10
  • Beacouse it's invoking immediately and it's not waiting for the data respond. Commented Dec 17, 2013 at 8:15
  • @OskarSzura But the data is coming asynchronously. Commented Dec 17, 2013 at 8:19
  • 1
    @OskarSzura I don't think the json variable will be undefined, because the the success function in $.ajax is a callback and will be executed once the AJAX request succeeds, so you can be sure that json there is never undefined. So I think going with the closure is a good idea. Commented Dec 17, 2013 at 8:19

1 Answer 1

5

Actually the JSON will not be undefined.
If you would break the following code apart it would become more clear:
So instead of this:

for (var index = 0; index < 4; index++) {
    (function(index){$.ajax({
        url: 'http://graph.facebook.com/',
        dataType: 'jsonp',
        success: function(json) {
            console.log(json[index]);
        }
    });
    })(index);
}

...you can also write it like this:

function myFunction(index) {
    $.ajax({
            url: 'http://graph.facebook.com/',
            dataType: 'jsonp',
            success: function(json) {
                console.log(json[index]);
            }
    });
}

// and call it like this

for (var index = 0; index < 4; index++) {
    myFunction(index);
}

As you might already see, how are any of those two variables going to change by another call while they are defined inside the function?

(On a side note: I think it actually looks cleaner this way)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.