New version of facebook type search box released on request
Facebook's search bar allows users to search for all users, communities, groups, apps and pages. It provides suggestions while typing. In this tutorial i'll explain you, how to create such a search input box in your website using jquery, ajax and php. I made the code short and simple to understand. Please suggest if any additional feature required.

Download ASP.NET Version
Configuring db.php
<?php
define('DB_SERVER', 'YOUR_DATABASE_SERVER');
define('DB_USERNAME', 'YOUR_DATABASE_USERNAME');
define('DB_PASSWORD', 'YOUR_DATABASE_PASSWORD');
define('DB_DATABASE', 'YOUR_DATABASE_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>
Creating the required tables in database
CREATE TABLE IF NOT EXISTS `test_auto_complete` ( `uid` int(11) NOT NULL DEFAULT '0', `username` varchar(30) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `media` varchar(200) NOT NULL, `country` varchar(200) NOT NULL );
The HTML
<div class="contentArea"> <input type="text" class="search" id="inputSearch" />Ex: swadesh, ipsita, dharitri<br /> <div id="divResult"> </div> </div>
The CSS
<style type="text/css">
body{
font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.contentArea{
width:600px;
margin:0 auto;
}
#inputSearch
{
width:350px;
border:solid 1px #000;
padding:3px;
}
#divResult
{
position:absolute;
width:350px;
display:none;
margin-top:-1px;
border:solid 1px #dedede;
border-top:0px;
overflow:hidden;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
-moz-border-bottom-right-radius: 6px;
-moz-border-bottom-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-width: 3px 1px 1px;
border-style: solid;
border-color: #333 #DEDEDE #DEDEDE;
background-color: white;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede;
font-size:12px; height:50px;
}
.display_box:hover
{
background:#3bb998;
color:#FFFFFF;
cursor:pointer;
}
</style>
The Javascript
$(function(){
$(".search").keyup(function()
{
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#divResult").html(html).show();
}
});
}return false;
});
jQuery("#divResult").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
$('#inputSearch').click(function(){
jQuery("#divResult").fadeIn();
});
});
The PHP Code
<?php
include('includes/db.php');
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="display_box" align="left">
<img src="<?php echo $media; ?>" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $country; ?></span></div>
<?php
}
}
?>
Fix
If you store firstname and lastname separately in your database, please update the line
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
with the following
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where lower(concat_ws(' ', firstname, lastname)) like '%$q%' or email like '%$q%' order by uid LIMIT 5");

Hello Ma'am!!!!
ReplyDeleteYour blog is quite excellent. Thanks a lot!!!!
I had 1 question related to this article!!!!
Can this same concept of 'facebook type search' be applied using asp.net or java instead of php???
bcoz i don't know php at all!!!!!
Its quite simple. Simply replace the php code (search.php + db.php) with your asp.net version. Everything else remains same.
ReplyDeletevery nice madam good job
DeleteOk,
ReplyDeletethank you for your reply!!!!
I'll try and work it out!!!
Keep up the good work!!!!
God bless u!!!!!!!
Hello Ma'am, I was successful in displaying the data using ASP.NET!!! Thanks a lot!!!!
ReplyDeleteBut ma'am there is one slight problem that i faced. Whenever i search for my data it appears perfectly but there is an image just like the blank textbox appearing at the last row!!!
What could be the problem ma'am?????
Can u upload your script somewhere so that i can check it out .
DeleteIn fact the image also acts like a textbox and searches the data!!!!
ReplyDeleteHello Ma'am the two jquery methods namely jQuery("#divResult") & jQuery(document).live are not getting executed in my program. So the data remains in the divResult as it is!!!! It does not go away if the textbox looses it's focus!!!
ReplyDeleteWhat should i do???
May be instead of .fadeOut() you could try .hide.
DeleteTry to check it with other browsers or other versions of jquery... I've checked it only with Google Chrome 21.0, Firefox 15.0 and IE 8
helo ma'am am still a student and i dont know php or javascript. PLs can you help me with some basic materials on both the php and javascripts and where i can get there compiler from.
ReplyDeleteYou can always go for http://www.w3schools.com/php/default.asp for basics of PHP and javasctipt. Learn the basics. Its always worth learning basics.
ReplyDeletehi hello from trinidad,well i am new to php and jquery i try out your code but i am having a problem. 1)i have two field in my database 1 for firstname and the other for lastname it work perfectly while typing the firstname but when i press space to continue to type the lastname is hide the DivResult and the search stops,what can i do to fixed this so i can type out the firstname press space to continue with the lastname.thanks much
ReplyDeleteToday I released a new version of this search script with more refinements and keyboard navigation support.
DeleteHello Eyaaz,
ReplyDeleteThanks for your query. I've updated the post and added solution to your query as a fix. Please check.
Hi again from Trinidad and Tobago, thank you for replying,it works perfectly,you are the best,thanks i can wait to show my classmates and pass on the knowledge,ill surely referred them to this site.thanks again
DeleteThis comment has been removed by the author.
DeleteHello Eyaaz,
ReplyDeleteThanks for your appreciation.
Hello Ma'am,
ReplyDeletejquery(document).live("click", function(e) {} function doesn't seem to get called in the code!!!!!
What should i do ma'am??????
Can you please tell me which browser and jquery version you are using.
DeleteVersion 22.0.1229.94 m and jquery-1.8.2.js. Also ma'am i have emailed my script to you, so you can check it out there too!!!!
DeleteThe script should work fine. Currently i'm facing some issue with my domain email. Can you send me your script to my personal email ID 2lessons@gmail.com
Deleteok ma'am, i've sent the mail!!!!
DeleteSorry Darrel for late reply.
DeleteFinally i uploaded a ASP.NET version of the facebook type autocomplete script(Find it near Download Script). Please check it. I hope it will solve your issue. If not please feel free to come back with your code.
Thanks a lot ma'am. It works great now!!!!!
DeleteNo problems at all!!!!!!
Thank you & God bless u!!!!!!
Nice to know that Darrel
DeleteHi
ReplyDeleteMissing jquery code for key navigation in the menu like Facebook has, and Enter (keyCode 13) for selections.
Any plans for integration this?
Today I released a new version of this search script with more refinements and keyboard navigation support.
DeleteHello,
ReplyDeleteThanks for pointing out the issue. Its really a handy part. I will try to integrate it.
Hello ma'am,
ReplyDeleteHow can we place the results of the search box over an already existing slideshow???
I've tried jquery methods like focus(), toggle(), etc but it didn't solve my problem!!!!
No matter what the slideshow always comes over the #divResult!!
I've sent a word document with the screenshot!!!
Please could you suggest what should be done to overcome this problem????
@darrel,
DeleteYou need to specify z-index in your CSS. A higher z-index will be placed above a lower one.
Thanks a lot ma'am!!!!
ReplyDeleteIt solved the problem!!!!!
Where can i learn more about css properties?????
Thanks a lot again & God bless u!!!
Hello Ipsita! I have a problem and I will be very happy if you could help me! At this page is an autocompleter http://blog.rarecore.eu/autocompleter-using-xajax.html .
ReplyDeleteIt works fine, but IT DOESN"T WORK for "Cote d'Ivoire" . The problem is "autocomplete apostrophe AND injection attack". I have read this page http://stackoverflow.com/questions/10054670/autocomplete-apostrophe-and-injection-attack , but isn't enough...
Could u help me? Thank u very much!
Sorry for late reply.
DeleteThere is a simple solution to your issue.
Simply add the fllowing at line-6 of "search.php"
$q=addslashes($q);
Thanks 4 your code..! But I m facing a little problem. i havn't able to select the autsuggest items by using my keyboard up and down key.
ReplyDeleteToday I released a new version of this search script with more refinements and keyboard navigation support.
Deletehttp://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html
Hello, Thanks for your complette code!
ReplyDeleteRegards, Trianta from Hungary
Hello,
ReplyDeleteCan you please tell me how can put 2 search box in one page?
Trianta
You just need to add the code for the textbox or input box.
DeleteFor example, in the 'Search Textbox' found in most of the sites!!!!!!!
Remember to change the name of the input box or textbox in your code!!!!
Hi,
ReplyDeleteThanks for the tutorial!
if i want to hide the div result when the search bar is no longer in use what should i do?
Thanks,
ids
Today I released a new version of this search script with more refinements and keyboard navigation support.
Deletehttp://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html
Hi mam can u tell how to create search box with autocompletion using jscript, php. Thanks in advance.
ReplyDeletehi thanks for the script, i have been searching for days to get something working and yours was so easy to impliment. had to change a few css things but all good.
ReplyDeleteissue i have is that instead of when clicking the name it go into search box i need it to go to url passing the id.
like users_detail.php?uid=
can you help please?
thanks again
Solution is pretty simple
DeleteInside index.htm -> insude the function jQuery("#divResult").live("click",function(e){
add the following at the end
window.location="searchResult.php?q="+decoded;
how would you use the GET method on a different variable, like if i wanted to pass the email variable?
DeleteNice post..
ReplyDeleteDear Mam....
ReplyDeleteThank you for your blog...Its an excellent one... But i have a problem.. click on the result doesn't work unless its the email.. i want the result when clicking on image and name too..can you help me.?
replace this code ....!!!!!
DeletejQuery("#divResult").click(function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("put tag close div tag here").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).click( function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
Today I released a new version of this search script. Probably this address your issue completely.
Deletehttp://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html
Dear Mam ....
ReplyDeleteThank you for your post it working fine for my query
Can your php code be replaced with Dreamweaver recordset? If so, can you please provide an example on how to do it. Your help would be highly appreciated.
ReplyDeleteits not working
ReplyDeleteu should replace 'live' with 'on'.
ReplyDeletejQuery("#divResult").live("click",function(e
How to make to tag multiple items
ReplyDeletethanks!!!!!!
ReplyDeletethanxs
ReplyDeletemadam your asp.net version is quite outstanding ..... But
ReplyDelete/*
String q=Request.Params[0];
con.Open();
cmd = new SqlCommand("select media,username,email,country from test_auto_complete where username like '%$q%' or email like '%$q%'",con);
*/
But above sql query does is not ok and does not hold the latest typed character from inputbox in the string Q;
Hi Ipsita. Please see my website, mipectower.com.vn, seacrch input in the MasterPage, it work good in default.aspx page, but in the other page i don't know why? here is my code in the search.ashx with url target, it's ok ?
ReplyDeleteResponse.Write("" + name_title + "");
Please check the path of the following file. It shows a not found error. http://www.mipectower.com.vn/ShopList.aspxSearch.ashx.
DeleteMy suggestion will be to use a absolute path. Because with url rewrite, the relative paths may not work well.
Can u help me fix this problem with url rewrite ? I really like this search box and want to apply this in my website like you see. Thank you so much.
DeleteTo do that probably i will have to access your code.
ReplyDeletecan u give me your email address? i'll send u.
DeleteI just fix this problem. Thanks :)
ReplyDeletehi maam nice tutorial. but i have a little issue when i click the name that appears in the search box it did not visit the profile of webpage the link shows under the person name. how can i do this? your reply really helps me. thanx
ReplyDelete@yes. even i'm facing the same issue. I will publish a new version by solving the issue soon.
DeleteToday I released a new version of this search script. Hope, this address your issue.
Deletehttp://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html
Nice code but I am having problem implementing it!I am using Mozilla Firefox 16.0.1 for ubuntu canonical 1.0 .I updated the server name,username password and database name in file as well as created the table using the same queries.PHP version:5.5.4 mysql:5.5.29.It seems Jquery code is not working.Can you please help me solving the problem?
ReplyDeleteWondегful blog! I found it while surfing arounԁ
ReplyDeleteon Yahoo News. Do you havе any suggеѕtions οn how to get
listed іn Yаhoo Νews? I've been trying for a while but I never seem to get there! Thank you
my web page: birmingham spa days
Hello Ma;am
ReplyDeletePlease let me know how to pass user id with user name?
Thank you
Use uid as "div-uid". Then while clicking the perticular div pass the uid as required.
DeleteThank you ma;am :)
DeleteToday I released a new version of this search script with more refinements and keyboard navigation support.
DeleteHello Maam,
ReplyDeleteI just need one solution that search should give result alphabatecally. I mean if i type "n" then name starting from "n" should only display
This is quite simple. You only need to change the search.php. Replace the line-6 with the following
Delete$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '$q%' or email like '$q%' order by uid LIMIT 5");
I just removed the first %
Anyway i will recommend check out the new updated facebook search script
http://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html?showComment=1368977317246#c6334945418322329527