Search code examples
javascriptjqueryfacebook-comments

Updating facebook comments plugin link without reloading page


This displays the comments from that http://domain.com/some/abc

<fb:comments href="http://domain.com/some/abc" num_posts="20" width="500"></fb:comments>
<div id="fb-root"></div>
<script type="text/javascript">
(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=1234567890";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>

If the user changes a value in the form from abc to xyz, I need the comment plugin to display comments from http://domain.com/some/xyz without reloading the page.

<form id="name">
    <select>
        <option value="abc" selected>abc</option>
        <option value="xyz">xyz</option>
    </select>
</form>

Is it feasible? (didn't find any information on the fb dev page.) I'm using jQuery. Thanks!


Solution

  • Yes, it is feasible; I believe I managed to replicate your desired result here;

    Snippet in case the jsfiddle dies:

    (function loadfb(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=1234567890";
        fjs.parentNode.insertBefore(js, fjs);
    })(document, 'script', 'facebook-jssdk');
    
    function changeDomain(value) {
        var newVal = '<fb:comments href="http://example.com/some/' + value + '" num_posts="20" width="500"></fb:comments><div id="fb-root"></div>';
        $('#comments').html(newVal);
        FB.XFBML.parse($('#comments').get(0),function(){
            $(".FB_Loader").remove();
        });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="name">
      <select onChange="changeDomain(this.value);">
        <option value="abc" selected>abc</option>
        <option value="xyz">xyz</option>
      </select>
    </form>
    <div id="comments">
      <fb:comments href="http://example.com/some/abc" num_posts="20" width="500"></fb:comments>
      <div id="fb-root"></div>
    </div>

    I did it by first replacing the innerHTML of the comments div(that I created to house the fb:comments tag), and then calling FB.XFBML.parse(); on that same comments div. Credit goes to this post which alerted me of that method.