Facebook like Autosuggestion with jQuery, Ajax and PHP.
Wall Script
Follow Me:
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=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; ?>&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.

121 comments:

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

    ReplyDelete
  2. 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!

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

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

    ReplyDelete
  5. 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

    ReplyDelete
  6. 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

    ReplyDelete
  7. 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

    ReplyDelete
  8. helo bro,
    u have treeview load from database?


    thanks

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

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

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

    because i newbie in js...

    please provide link event too..

    ReplyDelete
  12. Hi,

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

    ReplyDelete
  13. I'm using it, thanks I'm from mandasa

    ReplyDelete
  14. 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.

    ReplyDelete
  15. this information most important for me.
    thanks...

    ReplyDelete
  16. it's cool..
    thanks for share..

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

    ReplyDelete
  18. Testing your comment box

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

    ReplyDelete
  20. 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

    ReplyDelete
  21. how cany i use it using the keyboard?

    ReplyDelete
  22. 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

    ReplyDelete
  23. 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…

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

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

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

    ReplyDelete
  27. 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 ?

    ReplyDelete
  28. 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!!

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

    ReplyDelete
  30. 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 :)

    ReplyDelete
  31. 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.

    ReplyDelete
  32. 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?

    ReplyDelete
  33. how to add links to the friends drop down?

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

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

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

    ReplyDelete
  37. 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
    });
    });

    ReplyDelete
  38. 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.

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

    ReplyDelete
  40. 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

    ReplyDelete
  41. 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.

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

    Thanks!

    ReplyDelete
  43. i just browse and find your web
    and it was GENIUUUUUSSSSS!!!!!!


    Love You from my bottom of my heart

    ReplyDelete
  44. 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

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

    ReplyDelete
  46. 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...

    ReplyDelete
  47. @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

    ReplyDelete
  48. 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....

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

    ReplyDelete
  50. can I hide result of search box.??

    ReplyDelete
  51. 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,

    ReplyDelete
  52. 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

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

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

    ReplyDelete
  55. arrow key are not working

    ReplyDelete
  56. 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?

    ReplyDelete
  57. 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

    ReplyDelete
  58. 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.

    ReplyDelete
  59. 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.

    ReplyDelete
  60. 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 :)

    ReplyDelete
  61. 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;
    });
    });

    ReplyDelete
  62. is possible to use a xml data ? without php

    ReplyDelete
  63. How get the sample user data into mysql database?

    ReplyDelete
  64. 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

    ReplyDelete
  65. really its works amazing.....

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

    ReplyDelete
  67. 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.

    ReplyDelete
  68. I really love facebook ralated tutorials...
    I have one here facebook like registration:

    http://tutorials-edongkoy.blogspot.com/2011/12/facebook-like-registration-with-jquery.html

    ReplyDelete
  69. Gud work.... but it shows only suggestion... but cant select any suggestions......?

    ReplyDelete
  70. i do agree with the above said comment of my friend... !!!

    ReplyDelete
  71. its cool, but cant navigate via Keyboard,

    ReplyDelete
  72. thanks bro , its really helpful

    ReplyDelete
  73. how 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

    ReplyDelete
  74. Can 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.

    ReplyDelete
  75. You can download config.php or db.php file from previous posts

    ReplyDelete
  76. Do you have a specific link for them, I have looked threw a bunch of previous one s

    ReplyDelete
  77. would really be great to have the keyboard arrows working as well

    ReplyDelete
  78. 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

    ReplyDelete
  79. So 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!

    ReplyDelete
  80. Hussein 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!

    Hussein 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.

    ReplyDelete
  81. Hi, a question, how I can get information of the selected item (id)? very important, please help

    ReplyDelete
  82. Hi,

    Is 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

    ReplyDelete
  83. Can someone please help with a clear click function for the result?
    I 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.

    ReplyDelete
  84. Hello people, for the click event and paste value here is my solution.

    Put 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();
    });
    });

    ReplyDelete
  85. hi srinivas change your like be like this %$q% to more right...;

    ReplyDelete
  86. but don't forget to filter your $q% before it to avoid sql injection..sorry to added this comment;

    ReplyDelete
  87. Hi Sergey,

    Where should I put
    < a href="#" title="" class="keywordclick">
    ?

    Thanks

    ReplyDelete
  88. Thank you, how to search infinity scroll big record

    ReplyDelete
  89. Hai,

    Its good one i appreciate Tamada. But if it can use by mouse down arrow and Up arrow then very nice.

    ReplyDelete
  90. Just want to say that I love you bro, thank you!

    ReplyDelete
  91. In order to make it disappear once the box is empty simple change in the Javascript

    if(searchbox=='')
    {
    }

    *****************************to**********

    if(searchbox=='')
    {
    document.getElementById('display').style.display = 'none';
    }

    ReplyDelete
  92. How Can i add submit buton

    ReplyDelete
  93. thanks buddy..

    ReplyDelete
  94. Anyone knows how to close the results div??
    Esc and clicking empty space does not work. :((

    ReplyDelete
  95. Hi all search just super,please tell me how to make the search results appear after the introduction of 3 characters. Please give your answer

    ReplyDelete
  96. Hi all search just super,please tell me how to make the search results appear after the introduction of 3 characters. Please give your answer

    ReplyDelete
  97. I 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

    ReplyDelete
  98. what to do with sql query, if i want first for who is already my friend and then non-friends.

    ReplyDelete
  99. Hide suggestions when clicked anywhere else..

    just add these line of codes -

    var box = $('#display');
    $(document).click(function() {
    box.hide();
    });

    ReplyDelete
  100. Small 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

    ReplyDelete
  101. Great blog. really helpful information.
    its working wonderful coding.. Thanks

    ReplyDelete
  102. Hi,

    Thanks 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.

    ReplyDelete
  103. can i integrate this live search to my existing custom made php social network.. ? I am trying it

    ReplyDelete
  104. how 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

    ReplyDelete
  105. Hi,

    Thanks for this awqesome Blog. This is really help me a lot.

    ReplyDelete
  106. has anybody found out the way to make the arrow keys work?

    ReplyDelete