Posting HTML5 Facebook Like AJAX Item Comments

Facebook instructs us to put the following code on our page:

<div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> 

Instead, I wrap it in a function:

 function ReloadSocialSharing() { //facebook (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=myappid"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } 

and name it inside: $(function () { }

Now my similar buttons and my comments through the Facebook panel appear and work fine. Then I make an AJAX call and insert the new html elements into my page. They already have matching Facebook labels similar to my original fields. I make my ajax call like this:

 $('#search').ajaxSubmit(GetSearchAjaxFormOptions(!isDefault, element)); function GetSearchAjaxFormOptions(displayResetPreferencesButton, giveMeFocus) { return { target: '#search-results', data: GetSearchData(), success: function () { RunAfterSearchResultsAreReturned(giveMeFocus) }, error: function (error) { alert("Oops. There was an error.") } }; } RunAfterSearchResultsAreReturned() { ........ ReloadSocialSharing(); } 

All of this works well, but the new elements of social sharing that were added through the Ajax call are not connected and do not work. What am I missing?

Thanks!

Note. I saw notes about using FB.XFBML.parse (); However, I am trying to avoid XFBML.

+6
source share
1 answer

The main reason your attempt is not working is related to this line:

 if (d.getElementById(id)) return; 

i.e. the code checks to see if there is currently a facebook script (which you added dynamically using the rest of the included code), and if it is, does not include it again. I believe that deduplication exists for some reason, and in any case, I tested re-running the code (assuming the script is added twice) without success.

I saw your note on XFBML, however calling FB.XFBML.parse() (without any arguments) seems to work even if the markup used is HTML5:

 setTimeout(function() { $('<div class="fb-like" data-send="false" data-layout="standard" data-width="450" data-show-faces="false" data-colorscheme="light" data-action="like"></div>').appendTo('#test'); FB.XFBML.parse(); }, 2000); 

Working example in jsFiddle .

+4
source

All Articles