Anonymous Anonymous - 2 months ago 13
JSON Question

Javascript Uncaught TypeError: Facebook Like Counter

I have the following script to get the amount of likes from a Facebook page:

$("#facebook-likes").each(function () {
var container = $(this);
var fburl = container.attr('rel');
$.ajax({
dataType: 'json',
type: 'GET',
url: 'https://api.facebook.com/method/fql.query',
data: {
query: 'SELECT like_count FROM link_stat WHERE url="' + fburl + '"',
format: 'json'
}
}).success(function (data) {
container.text(data[0].like_count + ' Likes');
});
});


When running the script I get the following error:


Uncaught TypeError: Cannot read property 'like_count' of undefined


I've searched the internet for a solution but I can't find one solving this problem. I hope someone can help me out!

Answer

FQL is deprecated, this is the correct API to get the likes of a Page:

https://graph.faebook.com/[page-id]?fields=fan_count

You can test it in the API explorer: https://developers.facebook.com/tools/explorer/?method=GET&path=page-id%3Ffields%3Dfan_count&version=v2.7

Be aware that this needs an Access Token, so you should not do that client side with an App Access Token. You should also consider caching the result, not to hit API limits if there are a lot of users.

More information about Tokens:

Comments