4

How do I insert the facebook comment plugin using javascript? My website is ajax-driven and I need to load/reload the facebook comment plugin depending on a hash (index.html/#frontpage) -> (index.html/#movie1). My first thought was to use innerHTML:

document.getElementById('facebook').innerHTML = "<div id='fb-root'></div><fb:comments href='http://viljegse.dk/' num_posts='10' width='572'></fb:comments></div>";

This however doesn't work, so I tried creating the elements and then appending them, but then there is the <fb:comments> element, which is a problem.

Best regards, Ulrik

Ulrik M
  • 163
  • 2
  • 10
  • Can't say that I entirely understand what you are trying to do, but what I *can* say is that you cannot do AJAX calls across domains (so mysite.com cannot make an ajax call to anything but mysite.com). You might be hitting problems with that. – riwalk Mar 15 '11 at 20:40
  • @Stargazer712, you are right, I will rewrite my question. – Ulrik M Mar 15 '11 at 20:50
  • Are you working on an iframe and XFBML or just FBML canvas? – Manuel Pedrera Mar 16 '11 at 13:53

2 Answers2

12

FB:Root should be a part of the page at build time, and use the Javascript provided by FB to asynchronously load Facebook JS libraries on document load....just like FB describe.

Then, insert the FB comments using

document.getElementById('theplace').innerHTML="<fb:comments blah blah blah></fb:comments>"

and THEN

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

This bit of code will initialise the FB:Comments.

You can see a working example of this on my page at Track Vision - races page I spent a while sweating on this code, but it's all functional now! FB documentation is shocking!

All the best

Tony Carbone
  • 484
  • 4
  • 10
  • Im sorry, but when you say fb:root im not sure what you mean. Is is the
    code what you are reffering to?
    – fernandohur Oct 02 '11 at 22:35
  • 1
    Yes, that's what I was referring to @Woojah. The first bit `code`
    `code` provides a target for Facebook to insert things into. The rest of the stuff you pasted is the javascript that calls out to Facebook and says "Hey can you send over all your Facebook API's and commands please". As I said, have a look at the "view page source" of [link](http://www.TrackVision.org/races.php) for an example of how it all comes together. Hope that helps
    – Tony Carbone Nov 29 '11 at 02:44
  • I just wanted to add to this that it also works with the HTML5 version of comments and with version 2 of the Facebook API. – kel Aug 05 '14 at 18:08
0

I was able to solve the problem calling FB.XFBML.parse on an onLoad() callback

fernandohur
  • 7,014
  • 11
  • 48
  • 86