0

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)
    });

};
Sotiris
  • 36,024
  • 11
  • 46
  • 80

1 Answers1

2

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.

Pointy
  • 371,531
  • 55
  • 528
  • 584
  • 1
    thanks, this works great, I never thought that the `document.write()` is the problems. Thanks again – Sotiris Mar 03 '11 at 15:37
  • Jquery template is great to construct html from a Json object, you should check it out https://github.com/jquery/jquery-tmpl and a tutorial http://www.borismoore.com/2010/09/introducing-jquery-templates-1-first.html – David Martinez Mar 03 '11 at 15:56