facebook friends autocomplete dropdown selector

2,423

February 5, 2012 by admin

Recently i was working on a project that required a facebook type friend selector. Now i have use these many times before, i did a quick search on the internet but couldn’t find one that would do what i wanted.

All i needed was a simple text box which when you start typing names the drop down gives you a list of suggested matches.

After a bit more research i decided to build one using Yahoos YUI Library,  I used the AutoComplete Control. You can find out more about the  Yahoo YUI library here:

http://developer.yahoo.com/yui/autocomplete/

we will also be using the facebook server side flow authentication. You can find out more from the link below

http://developers.facebook.com/docs/authentication/#server-side-flow

Brief 

A text box which will list matches based on a users input in a scrollable drop down menu. Selected item must equate to the corresponding facebook id.

Resources 

Yahoo YUI Autocomplete Control
facebook Open graph API
Hosting Server Apache

 

First step is to include all the necessary library from  Yahoo YUI in your script

[HTML]

<!– Combo-handled YUI CSS files: –>
<link rel=”stylesheet” type=”text/css” href=”http://yui.yahooapis.com/combo?2.9.0/build/autocomplete/assets/skins/sam/autocomplete.css”>
<!– Combo-handled YUI JS files: –>
<script type=”text/javascript” src=”http://yui.yahooapis.com/combo?2.9.0/build/yahoo-dom-event/yahoo-dom-event.js&2.9.0/build/animation/animation-min.js&2.9.0/build/datasource/datasource-min.js&2.9.0/build/autocomplete/autocomplete-min.js”></script>

[/HTML]
It may look quite lengthy but they contain all the scripts required to let the control render.
Next will be to get the users friends. in this article im using purely php and facebook open graph. The below script will prompt  authentication and get the users friends. Sanitize the json.

[PHP]

<?php

define(‘APP_ID’, ‘xxxx’);//your app id
define(‘SECRET_KEY’, ‘xxxx’);//your app secret key
define(‘ROOT_LOCATION’, ‘xxxx’); //full path to where your script recides on your server
define(‘LIMIT’, 200); //put the limit of friends you want to retrieve in here no quotes i.e define(‘LIMIT’, 50);
session_start();
$code = $_REQUEST["code"];
$app_id = APP_ID;
$app_secret = SECRET_KEY;
$my_url = ROOT_LOCATION ;

 

if(empty($code)) {

$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = “http://www.facebook.com/dialog/oauth?client_id=”
. $app_id . “&redirect_uri=” . urlencode($my_url) . “&state=”
. $_SESSION['state'];

echo(“<script> top.location.href=’” . $dialog_url . “‘</script>”);
}

if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = “https://graph.facebook.com/oauth/access_token?”
. “client_id=” . $app_id . “&redirect_uri=” . urlencode($my_url)
. “&client_secret=” . $app_secret . “&code=” . $code;

$response = @file_get_contents($token_url);
$params = null;
parse_str($response, $params);

$graph_url = “https://graph.facebook.com/me/friends?access_token=” . $params['access_token'].”&fields=name,id&limit=”.LIMIT;

$preData = json_decode(file_get_contents($graph_url), true);
unset($preData['paging']);

$data = json_encode($preData, true);

}
else {
echo(“The state does not match. You may be a victim of CSRF.”);
}
?>

[/PHP]

 

Now that we have got a clean json of the users friends list lets pass it to the Yahoo data object.This is a combination of php and javascript. Because server script (in this case PHP) renders before client scripts(javascript) we can pass the friendslist  json to the yahoo YUI data Object.

[HTML]

<script type=”text/javascript”>
YAHOO.example.Data = <?php print_r($data); ?>
</script>

[/HTML]

Now lets create our form which will house a textbox and submit button.The form will also have an hidden field to store the selected friends id which you can then use as required.

[HTML]
<form id=”myForm” action=”#”>
<img src=”/images/fb-520.png” width=”300″ height=”90″ alt=”fb-520.com” title=”fb-520.com” />
<p><center>
facebook friend autopopulate selector
</center></p>
<div id=”myAutoComplete”>
<input id=”myInput” type=”text”><input id=”mySubmit” type=”submit” value=”Submit”>
<div id=”myContainer”></div>
</div>
<input id=”myHidden” type=”hidden”>
<!–<p><a href=”/wp-subscribers/verify.php?df=fb_auto_selector.zip”>Download the script now</a> | <a href=”/wp-subscribers/verify.php?df=fb_auto_selector.zip”>Back to article</a></p>–>
</form>

[/HTML]

Also include this css to style it as required

[CSS]

<style>
body{
margin:0 auto;
padding:0;
width:300px;
font-family:Verdana, Geneva, sans-serif;
font-size:12px;

}
#mySubmit {
margin-left:0.5em;
width:80px;
height:20px;
border:1px solid #ccc;
color:#FFFFFF;
background-color:#6D84B4;
font-size:12px
}
#myInput{
width:200px;
height:20px;
border:1px solid #069;
color:#666;
font-size:12px;
}
#myAutoComplete {
width:300px;
padding-bottom:1em;
font-size:12px;
}
#myAutoComplete ul{
color:#06C;
list-style:none;
margin:0;
padding:1px;
background:#efefef;
border-left:1px solid #6D84B4;
border-right:1px solid #6D84B4;
border-bottom:1px solid #6D84B4;
line-height:20px;
max-height:187px;
overflow-x:hidden;
overflow-y:auto;
width:200px;
}
#myAutoComplete ul li{cursor:pointer;
border-bottom:1px dotted #6D84B4;
padding-left:5px;
cursor:pointer;
}
#myAutoComplete ul li:hover{
background:#6D84B4;
color:#fff;
}
</style>

[/CSS]

Finally letes use the Yahoo YUI Library loaded from earlier to do the dirty work. This will load the data object and sort the data according the the matched entry in the textbox.

[HTML]

<script type=”text/javascript”>
YAHOO.example.ItemSelectHandler = function() {
// Use a LocalDataSource
var oDS = new YAHOO.util.LocalDataSource(YAHOO.example.Data.data);
oDS.responseSchema = {fields : ["name", "id"]};

// Instantiate the AutoComplete
var oAC = new YAHOO.widget.AutoComplete(“myInput”, “myContainer”, oDS);
oAC.resultTypeList = false;

// Define an event handler to populate a hidden form field
// when an item gets selected
var myHiddenField = YAHOO.util.Dom.get(“myHidden”);
var myHandler = function(sType, aArgs) {
var myAC = aArgs[0]; // reference back to the AC instance
var elLI = aArgs[1]; // reference to the selected LI element
var oData = aArgs[2]; // object literal of selected item’s result data

// update hidden form field with the selected item’s ID
myHiddenField.value = oData.id;
};
oAC.itemSelectEvent.subscribe(myHandler);

// Rather than submit the form,
// alert the stored ID instead
var onFormSubmit = function(e, myForm) {
//Put your script to submit the form here
//i.e document.myForm.submit
//or if using ajax put your jquery here. you do not need to include the library
YAHOO.util.Event.preventDefault(e);
//Test
alert(“facebook ID: ” + myHiddenField.value);
};
YAHOO.util.Event.addListener(YAHOO.util.Dom.get(“myForm”), “submit”, onFormSubmit);

return {
oDS: oDS,
oAC: oAC
};
}();
</script>

[/HTML]

If you look carefully above at the last code there is an event listener which has a function onFormSubmit – use this to grab the facebook id of the selected item and pass it as you require. In this example i have just bind it to an alert to confirm or show the selected user id when the submit button is clicked.

If you done everything right  upload the file to a php enabled server and your facebook friends autocomplete selector should look like this below.

facebook_autocomplete_selector

This could probably be built to be more efficient. I have not tested it with over 500 friend list so let me know if it works well for you.

Click here for a life example 

Like now to activate download link[like-gate]

Download the source  here 

[/like-gate]