While building my new blog's comment system I decided to just be lazy and use some other api. For this I decided to use the facebook API. I had previously built a comment system using a modified PHP API, but this time I had no reason to need to run it through my own backend.
Adding the comment box is extremely simply and only needs to use the fb:comments XFBML. it looks a little like this.
<fb:comments
url="http://devin.co/blog/ID"
xid="devin-blog-ID"
numposts="100"
width="650">
</fb:comments>
By specifying a url we can make sure that the likes for the page stay the same even if the title or url of the page changes slightly.
Now that I can receive comments and likes, I needed to get a summary of this info for multiple blog entries on the main blog page. I could have easily added a like button or looped through all the blog entries and queried them with fql.query, but I wanted to get all the info all at once.
My html markup looks something like this
<div class="blog-entry" xid="devin-blog-ID">
<div class="blog-info-item blog-info-comment">
<span class="blog-info-text">0</span>
</div>
<div class="blog-info-item blog-info-like">
<span class="blog-info-text">0</span>
</div>
</div>
Next I want to loop through all of the blog elements and build a multiquery for fql. Then loop through all the results and update all the blog entries with their counts.
q = '';
// loop through each blog element
$('.blog-entry').each(function(i) {
// add the comments count query
q +=
(q ? ',' : '') +
'"blog-query-' + (i*2+1) +
'": "select count from comments_info where xid=\'' + $(this).attr('xid') + '\' and app_id=' + FB._apiKey + '"';
// add the like count query
q +=
',"blog-query-' + (i*2+2) +
'": "select like_count from link_stat where url=\'http://' + window.location.hostname + '/blog/' +
$(this).attr('xid').replace(/^.*-([\d]+)$/,'$1') + '\'"';
});
q = '{' + q + '}';
// send the api request
FB.api(
{
method: 'fql.multiquery',
queries: q
},
function(r) {
$('.blog-entry').each(function(i) {
for (x in r) {
if (r[x].name == 'blog-query-'+(i*2+1)) {
// assign the count of the comments
$(this)
.find('.blog-info-comment .blog-info-text')
.html(r[x].fql_result_set.length ? r[x].fql_result_set[0].count : '0');
} else if (r[x].name == 'blog-query-'+(i*2+2)) {
// assign the count of the likes
$(this)
.find('.blog-info-like .blog-info-text')
.html(r[x].fql_result_set.length ? r[x].fql_result_set[0].like_count : '0');
}
}
});
}
);