0
var members = ['herpaderpus', 'turtles_head', 'nubstep_rs', 'ardens_fide', 'newending', 'pve_bros', 'rsphilippe', 'pureismwars', 'smap51', 'iprimal_rs', 'im_mr_bloo', 'mrknowles100', 'aikohero', 'cowsbelieve', 'dombo_12', 'diovista', 'mrpixels17'];
var memberData = [];

$.each(members, function(index, member) {
    $.getJSON('https://api.twitch.tv/kraken/users/' + member + '?callback=?', function(d) {
        if(d.status == 404) {}
        else {
            var data = [];
            data[0] = member;
            data[1] = d.display_name;
            memberData.push(data[0]);
                $.getJSON('https://api.twitch.tv/kraken/streams/' + data[0] + '?callback=?', function(d) {
                    if(d.stream != null) { 
                    $( "#player" ).append( "<img src='http://pso-clan.com/twitch/lib/images/online.png'>" + "<a target='_blank' href='http://www.twitch.tv/" + data[0] + "'>" + data[1] + "</a>" + " - Viewers: " + d.stream.viewers + "<br>" );
                    }
              else {
                    $( "#offline" ).append( "<img src='http://pso-clan.com/twitch/lib/images/offline.png'>" + "<a target='_blank' href='http://www.twitch.tv/" + data[0] + "'>" + data[1] + "</a> - Offline<br>" );

                    }

            });
        }   
    });
 }); alert(memberData[0]);   

I don't seem to be able to call

memberData.push(data[0]);

in the place where it's right now, the alert just show undefined. Why doesn't it properly push the member to the memberData array?

1 Answers1

1

You're actually incorrect - where you're using .push() is just fine (in the callback of your first $.getJSON() request).

Where you're alerting it, however is not, because this is an asynchronous request, whereby the alert occurs before the first ajax request is complete.

Take a look at the console output here: http://jsfiddle.net/remus/spSxE/ -- you'll see that undefined appears before any of the array push logging.

Options:

  • Rewrite your method to use parallel ajax requests like the solution here
  • Write the necessary DOM update functions (or whatever you're doing with the results) into the callback of each ajax request so that it is updated after each call completes.
Community
  • 1
  • 1
brandonscript
  • 68,675
  • 32
  • 163
  • 220