Sotiris
Sotiris

Reputation: 40046

using $.getJSON within a loop

Itry to learn a little bit JSON playing with facebook Graph API.

What I try to do: I have a list of football teams, and their IDs of its group in facebook. The teams are saved in the team array and the facebook IDs in the teamID array. Then I create a loop calling a function which contains $.getJSON and try to retrieve the likes of each group. The problems is that it prints only the first team and then the browser window just loading without populate the rest results.

I have the following code:

var team = ['aek','ael','aris','iraklis','kavala'];
var teamID = ['110422719032276','129322810472059','182829608421864','191854030839850','192175080800352']

$(document).ready(function() {
    for(var i=0; i<5; i++) {
    retrieveData(team[i],teamID[i]);
    }

});

function retrieveData(teamName,id) {
    var baseURL = 'http://graph.facebook.com/';
    $.getJSON(baseURL+id+"&callback=?", function(data) {
        document.write(teamName+" :"+data.likes)
    });

};

Upvotes: 0

Views: 2307

Answers (1)

Pointy
Pointy

Reputation: 413720

That's not far from correct, but you can't use document.write() to put your fetched data into the page. Instead, you're going to have to add stuff to the DOM, as necessary.

For example, you could do something like this:

function retrieveData(teamName,id) {
    var baseURL = 'http://graph.facebook.com/';
    $.getJSON(baseURL+id+"&callback=?", function(data) {
        $('#teamList').append('<div>' + teamName+" :"+data.likes + '</div>')
    });

};

if you had something like this:

 <div id='teamList'>
   <!-- teams go here -->
 </div>

on the page.

Upvotes: 2

Related Questions