Search Facebook Friends and Liked Pages Using PHP Ajax FQL

by  
Share:
facebook

In this tutorial I will be demonstrating you how to make the facebook like autosuggestion search  feature to find facebook friends and your liked pages using php, fql and ajax. If you have a database and want to fetch the records from there but you want the search to look like facebook search, then you have come at the right place. I will be showing you the search demo with your live facebook data.  You will need to create an application. If you need help in creating an application you can learn it here.

Search Facebook Friends

Create a form with input box.

To start things off you need to create a form where user can enter friends name. Add a div with an unique id to which you will add the results. In my case I have name the id as friendsResults.

<div class="search_tab">
        <div class="ser_ct">
          <input type="text" id="q" name="q" autocomplete="off"  value="" placeholder="search friends" />
        </div>
        <div class="ser_rt">
          <input class="app_sr_btn" type="submit" value="Search" />
        </div>
</div>
<div id="friendsResults" style="display:none;"></div>

Get all friends data via fql query.
//get all your friends
try {

	$fql    =   "SELECT uid, name, pic_square, first_name, last_name, profile_url, hometown_location.city, hometown_location.country  FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1 = me() )";
	$param  =   array(
		'method'    => 'fql.query',
		'query'     => $fql,
		'callback'  => ''
	);
	$friends   =   $facebook->api($param);

	// encode the results in json format
	$totalFriends = (json_encode($friends)); 

} catch (FacebookApiException $e) {
	#debugResults($e);
}

Bind the input box with a event listener.

Binding the input box with an event listener, so when you type any key the relevant code will be executed to search for the particular friends. An ajax query is triggered every time any key is pressed.

$(document).ready(function() {

$("#q").keyup(function() {
	keyword = $.trim($("#q").val());
	//alert(keyword+" "+keyword.length);
	if ( keyword.length > 0) {
		working = true;
		var friends = '<?php echo $totalFriends; ?>';
		var datstring = { name: keyword,  friends: friends };

		$.ajax({
			type: "POST",
			url: "getfriends.php",
			data: datstring,
			cache: true,
			beforeSend: function() {
				$("#friendsResults").html('<img src="images/ajax-loader.gif" width="24" height="24" border="0" style="padding-left:280px;" />').slideDown( "slow");
			},
			success: function(html) {
				$("#friendsResults").html(html).show();

			}, 
			error:function(html) {
				//$("#friendsList").html(html).show();
				//alert("Failed to fetch list of friends");
			}
		});	
	} else {
			$("#friendsResults").css("display", "none");;
	}

});

});

Filters the results by the keyword :: getfriends.php
<?php
function string_begins_with($string, $search) {
    return (strncasecmp ($string, $search, strlen($search)) == 0);
}

$friends = json_decode(stripslashes($_REQUEST["friends"]));
$name = $_REQUEST["name"];
$resultsData = array();
$counter = 0;
for ( $i = 0;  $i < count($friends); $i++ )  {
	if ( (string_begins_with($friends[$i]->first_name , $name ) !== FALSE ) || (string_begins_with($friends[$i]->last_name , $name ) !== FALSE ) ) {	
		$counter++;
		if ( strlen($friends[$i]->hometown_location->city) > 0 && strlen($friends[$i]->hometown_location->country) > 0) 
			$userLocation =  $friends[$i]->hometown_location->city. ', '. $friends[$i]->hometown_location->country;
		if ( strlen($friends[$i]->hometown_location->city) > 0 && strlen($friends[$i]->hometown_location->country) == 0) 
			$userLocation =  $friends[$i]->hometown_location->city;
		if ( strlen($friends[$i]->hometown_location->city) == 0 && strlen($friends[$i]->hometown_location->country) > 0) 
			$userLocation =  $friends[$i]->hometown_location->country;

		if ($counter > 5 ) { break; } else {
	?>
	<div class="box"> 
		<a href="<?php echo $friends[$i]->profile_url; ?>" target="_blank" title="Go to <?php echo $friends[$i]->name; ?> profile">  <span class="boximg">
			<img src="<?php echo $friends[$i]->pic_square; ?>" width="40" height="40" border="0" /></span> 
			<span class="boxname"><?php echo $friends[$i]->name; ?></span> 
			<span class="boxnamesmall"><?php echo $userLocation; ?></span> 
		</a> 
	</div>
    <?php
		}

	}
}
?>
<div class="box_more"><a href="#"> <span class="searchmore">Search more results for "<?php echo $name; ?>"</span></a></div>

Logic behind the total code.

Well nothing much fancy code, I have just bind the input box with the keyup event, so when the key is pressed, an ajax function is called which calls getfriends.php page. That php page searches for the match for the keyword and return the data. After a successful data interchange I just print the data inside the result container. Well you guys must be thinking that why I passed the whole list of friends data as a parameter every time through the ajax function, So the answer is quite simple. If you don’t pass the friends data list every time you will have to fetch the data from execution a fql which has an overhead and make the processing slow. I hope you get my point.

Search facebook liked pages

Same as above, create a form, bind the event, get the result and display it. Just fetch all your liked pages by this fql.

try {

	$fql    =   "SELECT name, type, pic_square, page_url FROM page WHERE page_id IN (SELECT uid, page_id, type FROM page_fan WHERE uid=me() ORDER by created_time DESC)";
	$param  =   array(
		'method'    => 'fql.query',
		'query'     => $fql,
		'callback'  => ''
	);
	$likePages   =   $facebook->api($param);

	// encode the results in json format
	$totalLikePages = addslashes(json_encode($likePages)); 

} catch (FacebookApiException $e) {
	#debugResults($e);
}

Filters the liked pages by the keyword: getpages.php.
<?php
function string_begins_with($string, $search) {
    return (strncasecmp ($string, $search, strlen($search)) == 0);
}

$like_pages = json_decode(stripslashes($_REQUEST["like_pages"]));
$name = $_REQUEST["name"];
$counter = 0;
for ( $i = 0;  $i < count($like_pages); $i++ )  {
	if ( (string_begins_with($like_pages[$i]->name , $name ) !== FALSE ) ) {	
		$counter++;		
		if ($counter > 5 ) { break; } else {
	?>
	<div class="box"> 
		<a href="<?php echo $like_pages[$i]->page_url; ?>" target="_blank" title="Go to <?php echo $like_pages[$i]->name; ?> profile">  <span class="boximg">
			<img src="<?php echo $like_pages[$i]->pic_square; ?>" width="40" height="40" border="0" /></span> 
			<span class="boxname"><?php echo $like_pages[$i]->name; ?></span> 
			<span class="boxnamesmall"><?php echo $like_pages[$i]->type; ?></span> 
		</a> 
	</div>
    <?php
		}

	}
}
?>
<div class="box_more"><a href="#"> <span class="searchmore">Search more results for "<?php echo $name; ?>"</span></a></div>

Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Franca Whyte on

Thank you for sharing this with us. It is really nice.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.