Search code examples
javascriptfacebook-graph-apifacebook-javascript-sdkasynccallback

Getting albums covers with facebook api


I'm trying to fetch albums list from facebook via JavaScript and Graph API. I'm doing it like this:

FB.api('/me/albums', function(response){
    //
});

Album covers coming back as photo id, not a url that I can insert into html. So, I need to get a urls in second step. But, by application design, I can't get urls later and insert images. I need to return a complete data object with album propereties (id, name, cover url). My last try is listed below:

FB.api('/me/albums', { fields : 'id,name,count,cover_photo' }, function(response){

    if (!response || response.error) {
        callback.call(false);
        return;
    };

    var parsed = $(response.data).map(function(){

        if (this.count > 0) {

            var result = {
                aid : this.id,
                title : this.name,
                cover : this.cover_photo
            };

            return result;
        };
    });

    for (var i = 0; i < parsed.length; i++) {

        (function(i){

            FB.api('/' + parsed[i].cover, { type : 'album' }, function(response){
                parsed[i].thumb = response.picture;
            });

        })(i);

    };

    callback.call(parsed);
});

The problem is that the loop is not waiting for cover queries and going forward, leaving return object without cover urls. I think it's can not be so difficult to do, but I can't find the solution long enough. Any ideas are welcome.


Solution

  • window.getAlbums = function() {
    FB.api({
         method: 'fql.multiquery',
         queries: {
            query1: 'select aid,name,link,photo_count,cover_object_id from album where owner = me()',
            query2: 'SELECT pid,src FROM photo WHERE object_id  IN (SELECT cover_object_id FROM #query1)'
         }
        },
        function(response) {
            var parsed = new Array();
            $(response[0].fql_result_set).each(function(index,value){
                    var result = {
                aid : value.aid,
                title : value.name,
                cover : response[1].fql_result_set[index].src,
                                link :value.link
            };
                    parsed.push(result);
            })
        getdata(parsed);
    });
    

    };

    Apped your album detail using

    function getdata(data){
    
    $(data).each(function(index,value){
        // console.log(value.aid + ' - '+ value.cover+ ' - '+ value.title );
        $("#fb_albumb").append('<h3>'+ value.title +'</h3><a href="'+ value.link  +'" target="_blank" ><img src="'+ value.cover +'" title="'+ value.title +'" /></a><br/>');
    })
    

    }

    HTML

    <fb:login-button scope="user_photos" onlogin="getAlbums()">Grant Permissions to Allow access to Photos and Albums</fb:login-button>
    

    May be this will help you.