Pepi San Pepi San - 1 month ago 22
Ajax Question

Facebook share button and Ajax

I'm working on a website refreshing a div content with differents articles. I have to put a Facebook share button for each article.
The refreshing is done in Ajax with jQuery

What I do :
with the article.php page called, I send an ID value. The URL looks like that :


http://www.website.org/index.php?page=article.php&id=892


In the index.php page, I've included :

<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script>
// 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/fr_FR/sdk.js#xfbml=1&version=v2.7";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

</script>


In the article.php page,

<div id="fb_container" class="fb-share-button" data-href="<?PHP
$url = "http://www.website.org/index.php?page=article?id=".$id;
echo $url;
?>" data-type="button_count">
</div>
<script>
$(document).ready(function() {
$('meta[property=og:title]').remove(); $('head').append('<?PHP echo $titre['contenu']; ?>');
// Same for the others meta tags

FB.XFBML.parse(document.getElementById('fb_container'));
});
</script>


The meta tags are updated, that's ok.
But the share button doesn't work :
- in the first load, it is visible but the shared page doesn't display the image and meta informations
- when we read another article, the share button isn't displayed

Any suggestion ?

Answer

I've find a solution using an another ajax called page including the Facebook link and the FB.ui function :

in the index.php :

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'Your id app',
      xfbml      : true,
      version    : 'v2.8'
    });
  };

  (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/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

function openFbPopUp(fburl,fbimgurl,fbtitle,fbsummary) {
FB.ui(
          {
            method: 'feed',
            name: fbtitle,
            link: fburl,
            picture: fbimgurl,
            caption: fbtitle,
            description: fbsummary
          }
        );  
}       

in the refreshed facebook.php page including the facebook share link :

// here the connection to the MySQL database
// read the values of the id element

<a onclick="openFbPopUp('<?PHP echo ($url_fb); ?>','<?PHP echo ("http://".$_SERVER['SERVER_NAME']."/".$photo['url_photo']); ?>','<?PHP echo ($titre['content']); ?>','<?PHP echo (substr(addslashes($description['content']),0,200)."..."); ?>')" value="SHARE">
<img src="images/fb-share.png">
</a>
Comments