Search code examples
javascriptjqueryfacebook-graph-apijquery-events

Looping through results in jQuery


I get stacked on a looping issue and couldn't get it.

for (var i = 0; i < count; i++) {
    FB.api({
        method: 'fql.query',
        query: 'SELECT name FROM user WHERE uid=' + temparray[i]
    }, function (response) {
        for (var x = 0; x < count; x++) {
            $("#divfather" + x).html(response[0].name);
        }
    });
}

The second loop is done through response[0].name which is the name of Facebook and showing me the same response for all divs.

I want only this second loop being done to the i variable.

How can I do it?


Solution

  • It's a little hard to understand what you want, but I assume you only want the i from the outer for loop.

    You'll need to create a new variable scope in order to retain it.

    for (var i = 0; i < count; i++) {
    
        FB.api({
            method: 'fql.query',
            query: 'SELECT name FROM user WHERE uid=' + temparray[i]
        }, (function( j ) {  // <---- create a function...
    
                    // v---------...that returns a function...
                return function (response) {
    
                   $("#divfather" + j ).html(response[0].name);
    
                };
    
            })( i ) // <------...and invoke it immediately, passing "i"
        );
    }
    

    Here's the same thing, but using a named function, which I think is a little nicer.

    function get_callback( j ) { 
    
        return function (response) {
    
           $("#divfather" + j ).html(response[0].name);
    
        };
    
    }
    for (var i = 0; i < count; i++) {
        FB.api({
            method: 'fql.query',
            query: 'SELECT name FROM user WHERE uid=' + temparray[i]
        }, get_callback( i ) );
    }
    

    Or personally, I'd place all the logic in the function instead of splitting it up.

    function set_up_FB_api( j ) { 
        FB.api({
            method: 'fql.query',
            query: 'SELECT name FROM user WHERE uid=' + temparray[ j ]
        }, function (response) {
    
           $("#divfather" + j ).html(response[0].name);
    
        });
    }
    
    for (var i = 0; i < count; i++) {
        set_up_FB_api( i );
    }