Question

I am having some trouble with the facebook like api. I am creating the like button with the following code:

<fb:like href="http://www.nettunes.co.za/artist_profile.php?ref=fb&amp;amp;artist_id=<?PHP echo $row->artist_id;?>&amp;amp;show=albums&amp;amp;sub_section=song&amp;amp;id=<?PHP echo $row->song_id;?>" layout="box_count" show_faces="false" width="50" font="arial" title="<?PHP echo ucfirst($row->song_name);?> by <?PHP echo $row->artist_name;?> on www.nettunes.co.za"></fb:like>

I am then listening for the event and calling a javascript function, that ajax runs a piece of PHP that inserts the like into the local database to keep track of all likes for this artist. using this code:

var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
  '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
    FB.Event.subscribe('edge.create', function(response) {
        var song_id = response.toString().split("&amp;id=");
        likeSong(song_id[1]);
    });

The problem is that it doesnt always call this likeSong function and add the like to the database.

Has anyone had a similar problem before? or do you know of a better way of doing this?

thanks so much

take care, Chregan

Was it helpful?

Solution

You probably need to wait for the Facebook library to be fully ready and check the response. You can do this with the fbAsyncInit method, which is called by Facebook once the library has loaded asynchronously:

<div id="fb-root"></div>
<script type="text/javascript" charset="utf-8">
window.fbAsyncInit = function() {
    FB.init({appId:"1234567890", status:true, cookie:true, xfbml:true, session:null});
    FB.Event.subscribe('edge.create', function(response) {
        if (response)
        {
            var song_id = response.toString().split("&amp;id=");
            likeSong(song_id[1]);
        }
    });
}

(function() {
var e = document.createElement("script");
e.src = document.location.protocol + "//connect.facebook.net/en_US/all.js";
e.async = true;
document.getElementById("fb-root").appendChild(e);
}());
</script>

You should also make sure that wherever likeSong is defined is initialized before the Facebook library loads and you add that event listener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top