9lessons programming blog
Loading Search
Monday, June 29, 2009

Facebook like Autosuggestion with jQuery, Ajax and PHP.

I received a lot of request from my readers that asked to me how to implement Autosuggestion search with jquery. I love facebook API it's neat, so I had developed Facebook like Autosuggestion user search with jQuery, Ajax and PHP. It's simple and clean just you have to change the database details.

Facebook like Autosuggestion with jQuery, Ajax and PHP.

Take a look at live demo, search word " sri "

Download Script     Live Demo

Download the Script. Edit Config.php change the database details.

Database
create database table with name "test_user_data"
CREATE TABLE test_user_data
(
uid INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(25),
lname VARCHAR(25),
country VARCHAR(25),
img VARCHAR(50)
);



Auto.html
contains jquery(javascript) and HTML Code. Take a look at input field class values search
<script type="text/javascript" src="jquery.js"></script>
</script>
$(document).ready(function(){
$(".search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{}
else
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}return false;
});
});
</script>

<input type="text" class="search" id="searchbox" />
<div id="display">
</div>

search.php
Contains PHP code. Display search results

<?php

include('config.php');
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=
mysql_query("select * from test_user_data where fname like '%$q%' or lname like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$fname=$row['fname'];
$lname=$row['lname'];
$img=$row['img'];
$country=$row['country'];
$re_fname='<b>'.$q.'</b>';
$re_lname='<b>'.$q.'</b>';
$final_fname = str_ireplace($q, $re_fname, $fname);
$final_lname = str_ireplace($q, $re_lname, $lname);

?>

<div class="display_box" align="left">
<img src="user_img/
<?php
echo $img; ?>" />
<?php echo $final_fname; ?>&nbsp;
<?php
echo $final_lname; ?><br/>
<?php echo $country; ?>
</div>
<?php

}
}
else
{}
?>

Using Watermark Input plugin
To show information about the contents of a text field.

<script type="text/javascript" src="jquery.watermarkinput.js"></script>
</script>
jQuery(function($){
$("#searchbox").Watermark("Search");
});
</script>

CSS
id #diplay overflow : hidden
*{margin:0px}
#searchbox
{
width:250px;
border:solid 1px #000;
padding:3px;
}
#display
{
width:250px;
display:none;
float:right; margin-right:30px;
border-left:solid 1px #dedede;
border-right:solid 1px #dedede;
border-bottom:solid 1px #dedede;
overflow:hidden;
}
.display_box
{
padding:4px;
border-top:solid 1px #dedede;
font-size:12px;
height:30px;
}
.display_box:hover
{
background:#3b5998;
color:#FFFFFF;
}


if any queries just post a comment.

Related Posts:

Facebook like suggestions with jQuery content appears and disappears.
Facebook like multi Toggle Comment Box with jQuery and PHP.
Submit multiple comment forms with jQuery and Ajax.
Sponsored Links

Share this post

Comments
{ 73 comments }
Yoosuf said...

its cool, but cant navigate via Keyboard, i guess better to use the LIveQuery Plugin

Arjen said...

This looks really good, I can probably use it in one of my projects, or I can try to integrate it with my wordpress blog.

Thanks for sharing this nice code!

haberler said...

wowww very good article . i will use this method in my new website..many many thanks.

Matt said...

The results disappear if you enter a space after 4 characters (search "Alex").

zamalek said...

this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
copy of this lesson on my site here www.7asryat.prnamg.net

www.ashrok.co.cc said...

this is the best tutorial .. i read it along times and i put a
copy of this lesson and all lessons here on my site here
www.ashrok.co.cc

dev on said...

can i put sql in to edurouteand read it from facebook

Myfacefriends said...

hi do you have mootols version of this? because where using mootols and we have problems using jquery in our site. thanks
http://myfacefriends.com

Rius said...

helo bro,
u have treeview load from database?


thanks

Anonymous said...

"The results disappear if you enter a space after 4 characters (search "Alex")" yes it disappear...but its really nice!!!

Anonymous said...

hi
Good example , but i think there click event is missing .

Picas said...

why the click event is missing..??
i stress to make it..

because i newbie in js...

please provide link event too..

Bruno said...

Hi,

Would it be possible to show a spinner or animated .GIF while he searches?

Anonymous said...

I'm using it, thanks I'm from mandasa

Anonymous said...

When converting this to asp. Is it request.form("search") or request.querystring("search")
Nothing works, since I'm using LIKE it will only display the 5 first results in DB.

And how to make the resultlist on top? All page moves down below resultlist for the moment.

www.ismakineleri.net said...

this information most important for me.
thanks...

Anonymous said...

it's cool..
thanks for share..

Kazi Mohammad Ekram said...

Thanks bro for sharing. Very nice article. I am going to use it for one of my project

Anonymous said...

Testing your comment box

Mukhtaruddin said...

Cool script..thanks for your share its free :)

Abdel-Rahman Awad said...

Hi thanks alot for all your efforts

i made a new auto complete plugin for auto complete which is very simillar to the Facebook search check it out

http://blog.halwsa.net/2010/jquery-autocomplete-search/

Cheers

Anonymous said...

how cany i use it using the keyboard?

Alvaro said...

hi, thanks for this script, i have one question. for what says this error :

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/ebox/public_html/ssss.com/search.php on line 8
?

the line 8, is while... any idea?. thanks for u help

Tutorials99 said...

Thanks for the this, it’s extremely extensive and useful!,do check out the link below

http://www.tutorials99.com

where all tutorials have a Higher page rank and professional.Very helpful for beginners…

Sandis said...

Wow, thank you, this is very useful... I like it very much. Nice job =)

stelios said...

it is easy to make results dissappear when you click somewhere else ?

Senja said...

Is wonderful

Thanks...

Anonymous said...

it only suggest but you can't click the results...

design web london said...

Thanks for this tutorial ..... i implemented it but i need to ask one thing when i use mouse to navigate it works but when i use keyboard then it wont can u please suggest how to resolve that issue ?

De Psicología said...

would love it if it could search multiple keywords in different columns like searching by name and country at the same time, typing "john england" to get results, and of course a keyboard event and onclick

that would make it perfect, but thanks alot for what you already gave to us!!

Anonymous said...

How can i make this dissapear onblur()? So when a user clicks or moves away from it the displaybox will dissapear?

Andrei Gabreanu said...

a) doesn't work with up/down
b) click on the result doesn't work unless its the title
c) if you type for example abcd and then go to the "b" with the cursor and type "@" it will try to find "bcd" (i think - it doesn't work in the end)
d) if you insert a token in the middle (not at the end of the text) it adds it at the end.

It was a nice try but could be done much better. Thanks for taking the time to share though :)

post said...

Hi there, great script.

But i have a problem, i would like solved :-).

When i input in the box, the display list, comes out on the left, in the < TD > table row, instead of under it. Screenshot: http://img707.imageshack.us/img707/8431/searchboxy.png.

My CSS Looks like this:

--------------------
*{
margin:0px
}

#searchbox {
width:250px;
border:solid 1px #000;
padding:3px;
}

#display {
width:250px;
display:none;
float:right;
margin-right:30px;
border-left:solid 1px #dedede;
border-right:solid 1px #dedede;
border-bottom:solid 1px #dedede;
overflow:hidden;
}
.display_box {
padding:4px;
border-top:solid 1px #dedede;
font-size:12px;
height:30px;
}

.display_box:hover {
background:#3b5998;
color:#FFFFFF;
}
-----------------------

The HTML code looks like this (some of it
...
....
.
..
< tr class="topMenu">< td class="topMenu">< IMG src="images/layout/logo.png">< td class="topMenuSearch">
< input type="text" class="search" id="searchbox" />
< div id="display">

< td class="topMenuRight">
.....
..
...
.

Search.php:
';
echo '< img src="' . $row[img] . '" />';
echo $row[name] . '
';
echo $row[cat];
echo '';
}
} else {

}
?>

And the AJAX code is untouched.

The problem might be in the CSS but i just got everything in here to be sure.

Would be glad, if anybody could help me out here ;-)!

See you all!

*made spaces in the HTML code, else it wont be posted.

Sonia said...

How do I make the drop down search contents click-able as in an anchor tag. I tried doing that by putting anchor tags around the image inside the display_box but then it stops showing any search results! Can you please suggest why?

Anonymous said...

how to add links to the friends drop down?

j0n4th4ntub3 said...

injection sql is posible... in the code but thanks anyway!.

nur1952 said...

click function is not working ... would you please clarify how to active click function ?

Anonymous said...

Nice Buddy
I Love u so Much u r Great Developer
I Love this Tutorial
How i COntact u Personal Email

jeannot said...

hi u all,Like u i was on stress because of the click event! I've come out with a solution it works but dont know if efficient have look :
-Create a link on the drop down list
-give it a class and so when on clik on it u gonna replace the value of the input by the value of the drop down here is the script:
$(function(){
$('.user').click(function(){//click on link user
var element = $(this);//identify the dropdown
var pseudo = element.attr("title");//register the user_nickname in a variable
$("#searchbox").val(pseudo);//replace the value of the input here
});
});

mail said...

Hi how would you make the display_box go over the text on the page like on facebooks search bar instead of moving all the text around on the page.

Anonymous said...

well done...i appreciated your work..keep it up..

rlsgame said...

Hi, can I integrate this script with joomla , I want just search for Articles name , no image , no info, Just Article Title, plz if Yes , can someone Help me to do that

Anonymous said...

Bravo! For all of you attempting to integrate, this is not for you - first learn JS, PHP, MYSQL, and CSS. Then attempt this tutorial. If you don't understand it, well then that just sucks, like joomla and wordpress.

Gonzalo Aguilera said...

Srinivas, very nice job. Would you please provide the JQUERY function to enable ONCLICK from the dropdown results? or a recommendation?

Thanks!

Auditya Nugraha said...

i just browse and find your web
and it was GENIUUUUUSSSSS!!!!!!


Love You from my bottom of my heart

hushtalk said...

i have the rest of the page moving down every time i do a search, any help on this please?

have a look here http://find-me.biz/findme

Anonymous said...

@author
how to prevent when user put "-" without quotation.. I found out it's not filtering some symbols thanks.

Martin said...

Hello im new here and new in the php world. i have really problems to realize this script and how to put this in my website. the tutorial can be made like step by step it will be nice. i upload the script to my host, but i don't have any idea how to make the other steps to make it work.. is there some other tutorial how to insert such scripts like this?
example
1. upload the file to your host.
2. make a new table.
3. put this or this so...in your .php
4...
5..

it will be nice...

Anonymous said...

@Matt The results disappear if you enter a space after 4 characters (search "Alex")

You have to change the sql query to solve this problem.
Try
Select * from test_user_data where concat(fname,' ',lname) like '%$q%' order by uid LIMIT 5"

Greetings bodhy

jesmin said...

wow wht gr8 idea to give service to web developers..thanx for ur writing...its really helpful 2me.i love web application...As i m beginner in this site...hope to c my self well developer..i m also working on blog.bt my topic is different this time.
http://ielts-programming.blogspot.com/
if its helps people i wll do my best to give best lik u....

Ketahui Selengkap nya Tentang Ku... said...

result in my site is bad...
when I type a-z or anything ..
and output text.. uhmm.
you know.
always Sri..

ruru said...

can I hide result of search box.??

hi said...

hmmm. nice nice

George said...

Has anyone managed to get the click function to work on this so we can click a suggestion and it will populate the input field with that selection.

Thanks In Advance,

Antonio Villalobos said...

Hi!
I have a problem, I want that when you click on a
the query line, I store that name in the input,
How do I do?

My email: antoniovillaglez@gmail.com

It's urgent

Rodney Nelson said...

How do i make it hide it if i click on a different form input

welcome to all in jacsi cse said...

I am javid from siber help .Amazing marvalous .Thank you .done Gr8 job

Anonymous said...

nice one

Anonymous said...

arrow key are not working

Josh said...

I got the click functions and multiple searches going, but I am unsure how to .hide the function if they end up not selecting from the drop down and erase and or click off the search bar... any ideas?

Amal said...

i have implemented this and made some edits (screenshot: http://tinypic.com/view.php?pic=kxdmp&s=7)

As some of the others, i would like to know how to do this
1) hide the div 'display_box' when i click somewhere else
2) how can i make the mysql values appear exactly like they appear in the database. For example, in my database i have a value called 'American' notice that the first A is capitalized. But when i start typinh in the search box as a.. then the search box shows 'american' and doesn't capitalize the first letter

Anonymous said...

can anybody tell me how can we get the results from two tables of database with single query by using this script.
single query that shows results of two tables of same database rest all features of this script same.

Anonymous said...

As for my Beta version of it, please go to www.riverpure.net. Its cool.


My name is Oliver Bob - Project lead of the Kingdom Social Network.

thebedjos said...

hello, some minus are it can't use keyboard naviation , and when i click on the result it cannot automatically fill in the text field. may be you can fix it. thanks :)

Anonymous said...

hey how do you do on jquery that if there is no text dat de display box fades out?

$(document).ready(function(){
$(".search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{}
else
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}return false;
});
});

Anonymous said...

is possible to use a xml data ? without php

topikutama.com said...

nice, imusing it. thanks

Anonymous said...

How get the sample user data into mysql database?

Anonymous said...

nice

Hugh Bellamy said...

Firstly, this is a great tutorial :).

However, are there are a few requests
A) to get the arrow keys working for easy navigation.
B) Hide when not clicked
C) Be able to type a space in

Anonymous said...

really its works amazing.....

Anonymous said...

Thank you Srinivas , it is the best script I've ever seen .

Hussein Sharif said...

For anyone looking to make the results clickable.

You simply use JQuery to listen for the "click" event on the "display-box" ID, when this happens, use $(this) to capture the "text()" of the img tag and set the "searchbox" "val" to the text variable.

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension