George
George

Reputation: 2110

PHP and JSON get followers count

Consider a javascript code snippet, which uses JSON to get twitter followers count. The problem is that I get the following: 'undefined 2146 Followers'. This script is meant for printng data about 4 twitter accounts. The code is as follows:

<div id='twitter'>
  <script type='text/javascript'>
    $(document).ready(function(){
      var i;
      twitterusername = ['Sinbg','followfog','miniclip','vgames'];
      for(i=0; i<4; i++){
        $.getJSON('http://twitter.com/users/' + twitterusername[i] +
                  '.json?callback=?', function(data){
          $('#twitter').html('' + twitterusername[i] + ' ' +
                             data.followers_count + ' Followers' + '<br/>');
        }); 
      }
    });
  </script>
</div>

Upvotes: 0

Views: 333

Answers (2)

Collin Green
Collin Green

Reputation: 2196

In addition to what kolink said, you're overwriting the contents of the twitter div so you only get the last output.

Here is all of it fixed: http://jsfiddle.net/fEfNr/

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

When the $('#twitter').html(...) part gets called, your for loop has ended and the value of i is 4. Consequently, twitterusername[4] is undefined.

To fix, structure your loop like this:

for( i=0; i<4; i++) {
    (function(i) {
        // your loop stuff here
    })(i);
}

This creates a new closure for i, effectively "anchoring" its value.

Upvotes: 2

Related Questions