integrate facebook like button with dynamically loaded content
Asked Answered
O

4

17

The website I am working on consists of a list of items dynamically loaded via AJAX. As you scroll down the page, more items are loaded.

Now my customer wants to add a Facebook like button (and the number of people who liked this) to each of these items.

Integrating the default like button is no problem, but how do I add the like button to the items loaded via AJAX? If a new item is loaded, how does the Facebook API know that there is a new like button in the DOM tree for which it needs to fetch the count of how many people liked this?

Has anyone experience in how to do this? Is there an example available? My search didnt turn up anything usefull except integrating the standard like button.

Overspend answered 26/3, 2011 at 8:10 Comment(1)
Why don't you accept an answer? It seems to me the question is answered.Temporary
R
44

Late answer, but you could use the parse function of the Facebook API in a callback of your function that loads the new elements to render the new like buttons:

FB.XFBML.parse();

You can also direct the parser to the elements you want rendered, so it doesn't re-render the already existing like buttons:

FB.XFBML.parse(document.getElementById('foo'));

This is straight from the docs: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/

Reina answered 6/7, 2011 at 10:48 Comment(1)
FYI, in my (limited) testing, FB.XFBML.parse() also parses the plain html versions of the facebook tags. IE a button specified like <div class="fb-login-button" ...></div> gets re-parsed. You don't have to use the FBXML tags like <fb:login-button ....></fb:login-button>Meritocracy
H
5

Late late answer but just in case someone need it.

Just finished my project nearly same as the one described. My page gets posts via ajax in json format, and i than create dom elements including facebook like button, tweet button and google plus one button. I ve had lots of problems until i get it right. Major problem was that like buttons didnt work as expected again and again... After while i found working solution.

I am using facebook js sdk (you can find some useful info here)

<div id="fb-root"></div>
<script>
  var isFBLoaded = false;
  window.fbAsyncInit = function() {
    FB.init({
        appId: ' your api key', 
        status: true, 
        cookie: true, 
        xfbml: false
    });
    isFBLoaded = true;
    ...
    renderFBqueue(); // i ll explain this later
  };
  (function() {
    var e = document.createElement('script'); 
    e.async = true;
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

It seems that there is a problem whit ajax content and FB.XFBML.parse() method or something. I found a solution on fb developers forum, and modified it to fit my needs. So after i get json content (multiple posts) from ajax call, i create all elements with jquery except fb like buttons. I put the post url (and some other related data) in queue and call function with timeout to create/parse those buttons.

var fb_queue = [];
...
function getMorePosts(){
    $.get('moreposts.php', params, function(response){
        if (response) createPosts(response);
    }, 'json');    
}
...
function createPosts(data){
    ...
    for (var key in data.posts) {
        ...
        fb_queue.push({ id : data.posts[key].id , url : data.posts[key].url });
    }
    ... // elements are created

}

and finaly to create and parse fb like buttons

function parseFBqueue(){
    if(isFBLoaded){
        if (fb_queue.length==0) return false;
        $.each(fb_queue, function (j, data) {
            window.setTimeout(function () { 
                renderFBLike(fb_queue.shift());  
            }, (j + 1) * 300); 
        });  
    };
}
function renderFBLike(data){
    var fblike = '<fb:like href="'+data.url+'" layout="button_count" ... ></fb:like>'
    $('#fbdiv-'+data.id).append(fblike);
    FB.XFBML.parse(document.getElementById('fbdiv-'+data.id'));    
}

Hope someone will find this useful, I know that I would a week ago :)

Highwrought answered 17/7, 2011 at 16:50 Comment(0)
P
0

The Facebook like button is just an <iframe> on the page. There is no "Facebook API" running, as such. The like count is part of the content inside of the <iframe>, and gets loaded with the rest of the content when the src URL is loaded by the browser. The code for a like button goes like:

<iframe src="http://www.facebook.com/plugins/like.php?href=YOUR_URL"
        scrolling="no" frameborder="0"
        style="border:none; width:450px; height:80px"></iframe>

So in essence, all you should need to do is add a new <iframe> to the page in the correct location and with the correct src URL, and all the rest will be handled automatically for you.

Pic answered 26/3, 2011 at 8:29 Comment(4)
Hm... I probably cant use the iframe version, I´dd rather use the Facebook Javascript APIOverspend
@Max - The JavaScript API still uses iframes, all it does is translate your <fb:like> tags into iframe elements, adding a handful of extra parameters to the iframe's src url. In practice it should not be too difficult to either precompute a like button with the desired properties using the JavaScript API and then copy the parameters into the iframe version, or to write your own simple JavaScript for transforming <fb:like> tags into the corresponding iframe.Pic
At the moment I am actually thinking about if this is actually doable the way the customer wants it... what he wants i actually to share the content of the item. But as far as I can see, it is only possible to share urls with the like button.Overspend
One argument against this method is that it could break if/when Facebook changes their embedding URL, while using the JavaScript API should work for the foreseable future.Romero
T
-4

call this javascript function after ajax complete ;)

fb_sharepro_render()
Tyrr answered 6/2, 2012 at 18:9 Comment(1)
this is a built in function inside the FB SDKTyrr

© 2022 - 2024 — McMap. All rights reserved.