Loading facebook social plugin into AJAX generated dynamic content. [Solved]

To include Facebook social plugins(ex: Facebook Comments http://developers.facebook.com/docs/reference/plugins/comments/) into our site, we use some java-script and some HTML structure provided by facebook. It works fine until you have AJAXified your pages. If your site refreshes each page on each request then facebook social plugins work perfect.
Problem occurs when the HTML structure is loaded via AJAX and the script used for FB is not called again after the ajax response. This happens because Facebook parses the page only on initial load and so doesn’t pick up the dynamic content. To make it work on AJAXified content, we need to explicitly tell it to re-parse the entire page, or just the new content.

Recently, I used a plugin called “Ajaxify WordPress Site” which makes a wordpress website completly AJAXified semlessly. Really nice plugin to ajaxify WP sites without any hassel, but one problem I faced with this was Facebook Comments not being rendered after AJAX response for which the answer is “FB.XFBML.parse()” function call.


1. JavaScript SDK which needs to be included once on the page.



2. HTML code to be placed wherever we want facebook plugin to appear on your page.



So, in our case, say this bit of HTML code comes dynamically with AJAX not on page refresh. So how can we display the facebook comments ?

Answer is simple: Call the ” FB.XFBML.parse() ” explicitly inside the AJAX success function, which will re-parse the html and render the Facebook comments section. 🙂

3. Code for AJAX success block with “FB.XFBML.parse()” call.

[php highlight=”15,16,17,18,19,20,21,22,23″]

// Ajax Request the Traditional Page
url: url,
success: function(data, textStatus, jqXHR){
// Prepare
$data = $(documentHtml(data)),
$dataBody = $data.find(‘.document-body:first’),
$dataContent = $dataBody.find(contentSelector).filter(‘:first’),
$menuChildren, contentHtml, $scripts;

//facebook comments
var isFacebook = $data.find(‘.fb-comments’);
if(isFacebook != ‘undefined’ ) {
var scriptText = ‘FB.XFBML.parse();’;
var scriptNode = document.createElement(‘script’);


Hope this will help someone solving facebook social plugin issue with AJAX content.. 🙂