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.
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)
);
(
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>
</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=mysql_real_escape_string(($_POST['searchword']);
//Old query
$sql_rees=
mysql_query("select * from test_user_data where fname like '%$q%' or lname like '%$q%' order by uid LIMIT 5");
//New query updated 04-02-2014
$sql_res=mysql_query("select * from test_user_data where (fname like '%$q%' or lname like '%$q%') OR (CONCAT(fname,' ',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; ?>
<?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>
</script>
jQuery(function($){
$("#searchbox").Watermark("Search");
});
</script>
CSS
id #diplay overflow : hidden
*{margin:0px}
width:250px;
border:solid 1px #000;
padding:3px;
}
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;
}
padding:4px;
border-top:solid 1px #dedede;
font-size:12px;
height:30px;
}
background:#3b5998;
color:#FFFFFF;
}
#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.
its cool, but cant navigate via Keyboard, i guess better to use the LIveQuery Plugin
ReplyDeleteThis looks really good, I can probably use it in one of my projects, or I can try to integrate it with my wordpress blog.
ReplyDeleteThanks for sharing this nice code!
wowww very good article . i will use this method in my new website..many many thanks.
ReplyDeleteThe results disappear if you enter a space after 4 characters (search "Alex").
ReplyDeletethis is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
ReplyDeletecopy of this lesson on my site here www.7asryat.prnamg.net
this is the best tutorial .. i read it along times and i put a
ReplyDeletecopy of this lesson and all lessons here on my site here
www.ashrok.co.cc
hi do you have mootols version of this? because where using mootols and we have problems using jquery in our site. thanks
ReplyDeletehttp://myfacefriends.com
helo bro,
ReplyDeleteu have treeview load from database?
thanks
"The results disappear if you enter a space after 4 characters (search "Alex")" yes it disappear...but its really nice!!!
ReplyDeletehi
ReplyDeleteGood example , but i think there click event is missing .
why the click event is missing..??
ReplyDeletei stress to make it..
because i newbie in js...
please provide link event too..
Hi,
ReplyDeleteWould it be possible to show a spinner or animated .GIF while he searches?
I'm using it, thanks I'm from mandasa
ReplyDeleteWhen converting this to asp. Is it request.form("search") or request.querystring("search")
ReplyDeleteNothing 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.
this information most important for me.
ReplyDeletethanks...
it's cool..
ReplyDeletethanks for share..
Thanks bro for sharing. Very nice article. I am going to use it for one of my project
ReplyDeleteTesting your comment box
ReplyDeleteCool script..thanks for your share its free :)
ReplyDeleteHi thanks alot for all your efforts
ReplyDeletei 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
how cany i use it using the keyboard?
ReplyDeletehi, thanks for this script, i have one question. for what says this error :
ReplyDeleteWarning: 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
Thanks for the this, it’s extremely extensive and useful!,do check out the link below
ReplyDeletehttp://www.tutorials99.com
where all tutorials have a Higher page rank and professional.Very helpful for beginners…
Wow, thank you, this is very useful... I like it very much. Nice job =)
ReplyDeleteit is easy to make results dissappear when you click somewhere else ?
ReplyDeleteIs wonderful
ReplyDeleteThanks...
it only suggest but you can't click the results...
ReplyDeleteThanks 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 ?
ReplyDeletewould 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
ReplyDeletethat would make it perfect, but thanks alot for what you already gave to us!!
How can i make this dissapear onblur()? So when a user clicks or moves away from it the displaybox will dissapear?
ReplyDeletea) doesn't work with up/down
ReplyDeleteb) 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 :)
Hi there, great script.
ReplyDeleteBut 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.
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?
ReplyDeletehow to add links to the friends drop down?
ReplyDeleteinjection sql is posible... in the code but thanks anyway!.
ReplyDeleteclick function is not working ... would you please clarify how to active click function ?
ReplyDeleteNice Buddy
ReplyDeleteI Love u so Much u r Great Developer
I Love this Tutorial
How i COntact u Personal Email
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 :
ReplyDelete-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
});
});
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.
ReplyDeletewell done...i appreciated your work..keep it up..
ReplyDeleteHi, 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
ReplyDeleteBravo! 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.
ReplyDeleteSrinivas, very nice job. Would you please provide the JQUERY function to enable ONCLICK from the dropdown results? or a recommendation?
ReplyDeleteThanks!
i just browse and find your web
ReplyDeleteand it was GENIUUUUUSSSSS!!!!!!
Love You from my bottom of my heart
i have the rest of the page moving down every time i do a search, any help on this please?
ReplyDeletehave a look here http://find-me.biz/findme
@author
ReplyDeletehow to prevent when user put "-" without quotation.. I found out it's not filtering some symbols thanks.
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?
ReplyDeleteexample
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...
@Matt The results disappear if you enter a space after 4 characters (search "Alex")
ReplyDeleteYou 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
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.
ReplyDeletehttp://ielts-programming.blogspot.com/
if its helps people i wll do my best to give best lik u....
result in my site is bad...
ReplyDeletewhen I type a-z or anything ..
and output text.. uhmm.
you know.
always Sri..
can I hide result of search box.??
ReplyDeletehmmm. nice nice
ReplyDeleteHas 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.
ReplyDeleteThanks In Advance,
Hi!
ReplyDeleteI 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: [email protected]
It's urgent
How do i make it hide it if i click on a different form input
ReplyDeleteI am javid from siber help .Amazing marvalous .Thank you .done Gr8 job
ReplyDeletenice one
ReplyDeletearrow key are not working
ReplyDeleteI 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?
ReplyDeletei have implemented this and made some edits (screenshot: http://tinypic.com/view.php?pic=kxdmp&s=7)
ReplyDeleteAs 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
can anybody tell me how can we get the results from two tables of database with single query by using this script.
ReplyDeletesingle query that shows results of two tables of same database rest all features of this script same.
As for my Beta version of it, please go to www.riverpure.net. Its cool.
ReplyDeleteMy name is Oliver Bob - Project lead of the Kingdom Social Network.
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 :)
ReplyDeletehey how do you do on jquery that if there is no text dat de display box fades out?
ReplyDelete$(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;
});
});
is possible to use a xml data ? without php
ReplyDeletenice, imusing it. thanks
ReplyDeleteHow get the sample user data into mysql database?
ReplyDeletenice
ReplyDeleteFirstly, this is a great tutorial :).
ReplyDeleteHowever, 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
really its works amazing.....
ReplyDeleteThank you Srinivas , it is the best script I've ever seen .
ReplyDeleteFor anyone looking to make the results clickable.
ReplyDeleteYou 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.
I really love facebook ralated tutorials...
ReplyDeleteI have one here facebook like registration:
http://tutorials-edongkoy.blogspot.com/2011/12/facebook-like-registration-with-jquery.html
Gud work.... but it shows only suggestion... but cant select any suggestions......?
ReplyDeletei do agree with the above said comment of my friend... !!!
ReplyDeleteits cool, but cant navigate via Keyboard,
ReplyDeletethanks bro , its really helpful
ReplyDeletehow do you create the database. Im super new to this but could someone upload a sample database that i could just add to my files and work off of. thank you
ReplyDeleteCan anyone explain the database as well. I know its been mentioned. But could someone post theres as a template idk how to do it. Very new.
ReplyDeleteYou can download config.php or db.php file from previous posts
ReplyDeleteDo you have a specific link for them, I have looked threw a bunch of previous one s
ReplyDeletewould really be great to have the keyboard arrows working as well
ReplyDeleteIm super new to this but could someone upload a sample database that i could just add to my files and work off of. thank you
ReplyDeleteSo cool, but PLEASE add the functionality to click on a search result and submit the form. I got everything else to work perfectly, but I don't know how to submit the form and load the results of the search!
ReplyDeleteHussein seems to have it figured out, but I don't know how to implement his solution. Please add that functionality to your downloadable files. Many people have posted same request!
ReplyDeleteHussein Sharif said...
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.
how to search unicode
ReplyDeleteHi, a question, how I can get information of the selected item (id)? very important, please help
ReplyDeleteHi,
ReplyDeleteIs there a way to search for keywords instead of a sentence?
It is like this, say i have 3 sentences.
- css border
- css without border
- css without css
If i search with the keywords 'css border', i want to find the first 2 sentences.
With the current settings i only find the first sentence.
How can i fix this?
Thanks
JayD
Can someone please help with a clear click function for the result?
ReplyDeleteI tried:
$(function(){
$('.click').click(function(){
var element = $(this);
var pseudo = element.attr("title");
$("#search").val(pseudo);
});
});
But i'm not sure if i'm doing it wrong or what.
Hello people, for the click event and paste value here is my solution.
ReplyDeletePut a not formated php variable to "title" link
< a href="#" title="" class="keywordclick">
and paste this code to search.php
$(document).ready(function(){
$('.keywordclick').click(function(){
$("#searchbox").attr("value", this.title);
$(".display_box").fadeOut();
});
});
hi srinivas change your like be like this %$q% to more right...;
ReplyDeletebut don't forget to filter your $q% before it to avoid sql injection..sorry to added this comment;
ReplyDeleteHi Sergey,
ReplyDeleteWhere should I put
< a href="#" title="" class="keywordclick">
?
Thanks
Thank you, how to search infinity scroll big record
ReplyDeleteHai,
ReplyDeleteIts good one i appreciate Tamada. But if it can use by mouse down arrow and Up arrow then very nice.
Just want to say that I love you bro, thank you!
ReplyDeleteIn order to make it disappear once the box is empty simple change in the Javascript
ReplyDeleteif(searchbox=='')
{
}
*****************************to**********
if(searchbox=='')
{
document.getElementById('display').style.display = 'none';
}
How Can i add submit buton
ReplyDeletethanks buddy..
ReplyDeleteAnyone knows how to close the results div??
ReplyDeleteEsc and clicking empty space does not work. :((
its working wonderful coding.. Thanks
ReplyDeleteHi all search just super,please tell me how to make the search results appear after the introduction of 3 characters. Please give your answer
ReplyDeleteHi all search just super,please tell me how to make the search results appear after the introduction of 3 characters. Please give your answer
ReplyDeleteI have implemented this. it worked very well . i want to expand it so that when i click on the searched user below i can navigate to another page where i can GET searched user id . please suggest some help .. thanks and regards
ReplyDeletewhat to do with sql query, if i want first for who is already my friend and then non-friends.
ReplyDeleteHide suggestions when clicked anywhere else..
ReplyDeletejust add these line of codes -
var box = $('#display');
$(document).click(function() {
box.hide();
});
nice tutorial
ReplyDeleteSmall update, it will replace the letters of the surname in bold
ReplyDelete$fname=$row['fname']; // first name
$lname=$row['lname']; // last name
$full_name = $fname . " " . $lname; // first name space last name
$re_full_name=''.$q.''; // bold
$final_full_name = str_ireplace($q, $re_full_name, $full_name); // search full name
Great blog. really helpful information.
ReplyDeleteits working wonderful coding.. Thanks
not working click event
ReplyDeleteHi,
ReplyDeleteThanks for this awqesome Blog. This is really help me a lot. I have query. If I need this search only with first letter of my friends name then how to do? I see here this search also collect a letter from inside the name. But I want only first letter. Please help.
Thanks.
can i integrate this live search to my existing custom made php social network.. ? I am trying it
ReplyDeletegre8 Example
ReplyDeletehow can i hide the menu if the menu is not clicked, and how can i send a php request if a item from the display is selected
ReplyDeleteHi,
ReplyDeleteThanks for this awqesome Blog. This is really help me a lot.
Great example! thanks
ReplyDeleteYes Great Example
ReplyDeletewonderful and example
ReplyDeletewonderful and example
ReplyDeleteThanks for this good Blog.
ReplyDeletehas anybody found out the way to make the arrow keys work?
ReplyDeleteHi there, This is exactly I am looking but can you help in implementing it in codeigniter framework...any modifications and suggestions would be of great help...
ReplyDeleteThanks
This is exactly I am looking forward to...looking forward to implement this codeigniter framework, any suggestions or modifications would be of great help.
ReplyDeleteThanks
ReplyDeleteVery Heplful Article
Check it Out
ReplyDeleteSmall update, it will replace the letters of the surname in bold
$fname=$row['fname']; // first name
$lname=$row['lname']; // last name
$full_name = $fname . " " . $lname; // first name space last name
$re_full_name=''.$q.''; // bold
$final_full_name = str_ireplace($q, $re_full_name, $full_name); // search full name
.
nice work sir thank you so much and keep it up
ReplyDeleteHow to select the suggestion list via keyboard arrows with hint's like Google search box.
ReplyDeleteawesome script sir thank you so much and more updates like that
ReplyDeletegood work nice work sir thank you so much and keep it up
ReplyDeleteHey, Sri. I love your work, but I gotta report a bug in the demo page: search.php is returning nothing (This request has no response data available), no matter what I type.
ReplyDelete