Kasper Christensen
Kasper Christensen

Reputation: 905

How can I do pagination when downloading facebook posts via javascript and FB.api?

I am trying to download facebook wall posts via the javascript SDK. I managed to do a call for the first 25 posts, but I get into trouble when I am trying to get paging.next and feed that into a new call using a loop, and then iterate over that until no more pages is available.

The code produces the same page 10 times which I do not understand. It should give the next page and the next page and the next page..?

FB.login(function(response){

        // FIRST CALL THAT CALLS FOR PAGENAME/FEED
        FB.api(request, function (response) {

            // PRINTS TO LOG AND DECLARES X AS THE NEXT PAGE
            console.log(response.paging.next);
            var x = response.paging.next;

            // LOOP THAT PREFERABLY SHOULD CONTINUE UNTIL NO MORE PAGES
            // BUT I WILL DEAL WITH THAT LATER
            for (i = 0; i < 10; i++) {

                // CALLS X WHICH ALSO GIVES ME RHE NEXT PAGE
                // BUT FOR SOME REASON THE CODE DOES NOT MANAGE TO CHANGE
                // X AND DO A NEW CALL
                FB.api(x, function (res){

                    console.log(i);
                    console.log(res.paging.next);
                    // HERE I RESPECIFY X
                    x = res.paging.next;

                    });

                };

           }

          ); 

    }, {scope: 'publish_actions'});

Upvotes: 1

Views: 1219

Answers (1)

andyrandy
andyrandy

Reputation: 73984

You need to learn how to deal with asynchronous JavaScript and how to do recursive functions. You are trying to use "x" before the asynchronous API call sets it. Meaning, the whole for loop finishes before "x" even gets set once - because the API call takes a while.

Here´s some quick code, did not test it but it should show one solution:

var items = [];
function apiCall(next) {
    FB.api(next, function (response) {
        for (var i = 0; i < response.data.length; i++) {
            //add all posts to the items array
            items.push(response.data[i]);
        }
        if (response.paging && response.paging.next) {
            //call function recursively until there is no "next"
            apiCall(response.paging.next);
        } else {
            //this is when it´s done
            console.log(items);
        }
    });
}
apiCall('/page-id/feed');

Make sure you understand the concepts, it´s very important to know when you deal with the JavaScript SDK and JavaScript in general.

Upvotes: 5

Related Questions