Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope problem with nested $.getJSON


$.getJSON('http://twitter.com/followers/ids.json?screen_name=/…'+ query1 + '&callback=?',
  function(data) {
    alert('JSON data string 1 is: '+data); 
    $.getJSON('http://twitter.com/followers/ids.json?screen_name=/…'+ query2 + '&callback=?', 
      function(data1) {
        alert('JSON data string 2 is: '+data1); 
        f2=data1; 
        f1=data; 
        for(var i=0; i "less than" f1.length; i++)
        {
          for(var j=0; j "less than" f2.length; i++)
          {
            if (f1[i] == f2[j])
            {
              common[c]=f1[i];
              c+=1;
            }
          }
        }
        $('#content').append(''+common.length+'');//this line is not working though....... 
    });
});

In this piece of the line

$('#content').append(''+common.length+'');

doesnt show the output actually it the page hangs

Any help will be appreciated.

Thank You

like image 496
anand Avatar asked Jan 19 '26 09:01

anand


2 Answers

Don't nest the calls. You also avoid some memory issues where javascript maintains a copy of all local variables for every anonymous function. By making the two calls separately you can also perform both calls at once instead of sequentially.

This is a better method if I understand your purpose. Plus by polling gotA and gotB you can even make a nice little "waiting for A, waiting for B" notification for users.

Edit: Added for loop fix from previous answer.

var gotA, gotB;
var followingA, followingB;
function getCommonFollowers(user1, user2)
{
    gotA = false;
    gotB = false;
    jQuery.getJSON('http://twitter.com/followers/ids.json?screen_name=/…'+ user1 + '&callback=?', gotFollowersOfA );
    jQuery.getJSON('http://twitter.com/followers/ids.json?screen_name=/…'+ user2 + '&callback=?', gotFollowerOfB );
}
function gotFollowersOfA(data)
{
    followingA = data;
    gotA = true;
    if (gotB) {
        compareFollowersAB();
    }
}
function gotFollowersOfB(data)
{
    followingB = data;
    gotB = true;
    if (gotA) {
        compareFollowersAB();
    }
}
function compareFollowersAB()
{
    f2=followingA; 
    f1=followingB; 
    for(var i=0; i < f1.length; i++) {
        for(var j=0; j < f2.length; j++) {
            if (f1[i] == f2[j]) {
                //console.log("Adding f1[i]");
                common.push(f1[i]);
            }
        }
    }
    $('#content').append(''+common.length+'');
}
like image 58
Great Turtle Avatar answered Jan 21 '26 23:01

Great Turtle


Your second for loop increments i instead of j.

You dont declare any of your vars which may lead to scope issues etc.

Can you paste your actual code, its a tough ask to expect anyone to diagnose the issue without your script.

Also create a demo of the issue at jsbin.com or pastebin.me while your at it.

like image 28
redsquare Avatar answered Jan 21 '26 23:01

redsquare