- Testing FQL Queries
- Finding the User's Friends
- Finding the User's Links
- Executing the FQL Queries
- Putting It All Together
- Summary
Putting It All Together
The sample "Friends and links" application (you can also view its source) is an extension of the simple Facebook login application I described in my earlier article "Use Facebook Connect to Bring Your Application to Millions of Users." Calls to two additional functions, showFriends and showLinks, were inserted in the fb_login function, which is executed after the user has logged into Facebook.
Both functions execute an FQL query, parse its results, and use jQuery calls to build parts of the HTML page. The simpler function also handles the user's friends; it executes the query and builds a list of friends' names:
function showFriends() { function buildFriendList(data) { // ... build the HTML ... } fb_uid = FB.Connect.get_loggedInUser(); FB.Facebook.apiClient.fql_query( "SELECT profile_url,name FROM user WHERE uid IN "+ "(SELECT uid2 FROM friend where uid1 = "+fb_uid+ " ORDER BY rand() LIMIT 20) "+ " ORDER BY name",buildFriendList); }
The buildFriendList function checks the size of the result set, returning immediately if the result set is empty. Otherwise, it builds simple HTML code and inserts it into the friendList DIV container:
function buildFriendList(data) { if (!data.length) return; var html = "<h3>List of friends</h3><p>" for (var i = 0; i < data.length; i++) { var row = data[i]; if (row.profile_url) html += "<a href='"+row.profile_url+"'>"; html += row.name; if (row.profile_url) html += "</a>"; html += "<br />"; } html += "</p>"; $("#friendList").html(html); }
The showLinks function is very similar to the showFriends function, but it needs a slightly more complex handling of the results:
function showLinks() { function buildLinkList(data) { // build HTML } fb_uid = FB.Connect.get_loggedInUser(); FB.Facebook.apiClient.fql_query( "SELECT url,title FROM link WHERE owner = "+fb_uid+ " ORDER BY created_time DESC LIMIT 10",buildLinkList); }
If the url field in the result row has a url property, the link points to another page within Facebook. If it's a string, the url field has to be used verbatim:
function buildLinkList(data) { if (!data.length) return; var html = "<h3>Your links</h3><p>" for (var i = 0; i < data.length; i++) { var row = data[i]; var url = row.url.url ? row.url.url : row.url.toString(); html += "<a href='"+url+"'>"+row.title+"</a><br />"; } html += "</p>"; $("#linkList").html(html); }