top_menu

Sunday, 23 September 2012

Facebook type search box with auto complete using jquery, ajax and PHP

.

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.

facebook like autocomplete search box


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>&nbsp;<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");

105 comments:

  1. Hello Ma'am!!!!
    Your 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!!!!!

    ReplyDelete
  2. Its quite simple. Simply replace the php code (search.php + db.php) with your asp.net version. Everything else remains same.

    ReplyDelete
    Replies
    1. very nice madam good job

      Delete
  3. Ok,
    thank you for your reply!!!!
    I'll try and work it out!!!
    Keep up the good work!!!!
    God bless u!!!!!!!

    ReplyDelete
  4. Hello Ma'am, I was successful in displaying the data using ASP.NET!!! Thanks a lot!!!!
    But 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?????

    ReplyDelete
    Replies
    1. Can u upload your script somewhere so that i can check it out .

      Delete
  5. In fact the image also acts like a textbox and searches the data!!!!

    ReplyDelete
  6. Hello 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!!!
    What should i do???

    ReplyDelete
    Replies
    1. May be instead of .fadeOut() you could try .hide.
      Try 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

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

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

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

    ReplyDelete
    Replies
    1. Today I released a new version of this search script with more refinements and keyboard navigation support.

      Delete
  10. Hello Eyaaz,

    Thanks for your query. I've updated the post and added solution to your query as a fix. Please check.

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

      Delete
    2. This comment has been removed by the author.

      Delete
    3. what if to show suggestion like user, group,pages ext with multi table.
      if some one type jo it will give show all user name,group,pages with jo
      all store in diffrent table

      Delete
  11. Hello Eyaaz,

    Thanks for your appreciation.

    ReplyDelete
  12. Hello Ma'am,
    jquery(document).live("click", function(e) {} function doesn't seem to get called in the code!!!!!
    What should i do ma'am??????

    ReplyDelete
    Replies
    1. Can you please tell me which browser and jquery version you are using.

      Delete
    2. Version 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!!!!

      Delete
    3. The 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

      Delete
    4. ok ma'am, i've sent the mail!!!!

      Delete
    5. Sorry Darrel for late reply.

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

      Delete
    6. Thanks a lot ma'am. It works great now!!!!!
      No problems at all!!!!!!
      Thank you & God bless u!!!!!!

      Delete
  13. Hi

    Missing jquery code for key navigation in the menu like Facebook has, and Enter (keyCode 13) for selections.

    Any plans for integration this?

    ReplyDelete
    Replies
    1. Today I released a new version of this search script with more refinements and keyboard navigation support.

      Delete
  14. Hello,
    Thanks for pointing out the issue. Its really a handy part. I will try to integrate it.

    ReplyDelete
  15. Hello ma'am,
    How 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????

    ReplyDelete
    Replies
    1. @darrel,

      You need to specify z-index in your CSS. A higher z-index will be placed above a lower one.

      Delete
  16. Thanks a lot ma'am!!!!
    It solved the problem!!!!!
    Where can i learn more about css properties?????

    Thanks a lot again & God bless u!!!

    ReplyDelete
  17. Ovidiu Toma (Romania)7 December 2012 at 14:02

    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 .
    It 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!

    ReplyDelete
    Replies
    1. Sorry for late reply.

      There is a simple solution to your issue.

      Simply add the fllowing at line-6 of "search.php"
      $q=addslashes($q);

      Delete
  18. 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.

    ReplyDelete
    Replies
    1. Today I released a new version of this search script with more refinements and keyboard navigation support.
      http://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html

      Delete
  19. Hello, Thanks for your complette code!
    Regards, Trianta from Hungary

    ReplyDelete
  20. Hello,
    Can you please tell me how can put 2 search box in one page?
    Trianta

    ReplyDelete
    Replies
    1. You just need to add the code for the textbox or input box.
      For 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!!!!

      Delete
  21. Hi,
    Thanks 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

    ReplyDelete
    Replies
    1. Today I released a new version of this search script with more refinements and keyboard navigation support.
      http://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html

      Delete
  22. Hi mam can u tell how to create search box with autocompletion using jscript, php. Thanks in advance.

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

    issue 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

    ReplyDelete
    Replies
    1. Solution is pretty simple

      Inside index.htm -> insude the function jQuery("#divResult").live("click",function(e){

      add the following at the end
      window.location="searchResult.php?q="+decoded;

      Delete
    2. how would you use the GET method on a different variable, like if i wanted to pass the email variable?

      Delete
  24. Dear Mam....

    Thank 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.?

    ReplyDelete
    Replies
    1. replace this code ....!!!!!


      jQuery("#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();
      }
      });

      Delete
    2. Today I released a new version of this search script. Probably this address your issue completely.
      http://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html

      Delete
    3. thankx alot mam for your great work.

      Delete
    4. Its happening same for me.
      var decoded = $("put tag close div tag here").html($name).text();
      can you suggest what to do here?

      Delete
    5. Hi,
      How to get value of name in text box? if he click any where on the #divResult means any result either image, name , second name or email.
      Thanks

      Delete
    6. Rajesh, please check out the newer version of facebook type search box. It address your question.

      Delete
    7. Hi,
      thanks i also check that but that is little heavy code.
      and i want to use after click a event to fire and get details from data base as in last version.

      jQuery(document).click(function(e) {
      var $clicked = $(e.target);
      if (! $clicked.hasClass("search")){
      jQuery("#divResult").fadeOut();

      var data=$("#inputSearch").val();
      alert(data);
      $.post('get_details.php', {data:data},
      function(data){
      output_string = jQuery.parseJSON(data);
      $("#result_table").html(output_string);
      });

      }
      });


      get_details.php


      Delete
  25. Dear Mam ....

    Thank you for your post it working fine for my query

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

    ReplyDelete
  27. its not working

    ReplyDelete
  28. u should replace 'live' with 'on'.


    jQuery("#divResult").live("click",function(e

    ReplyDelete
  29. How to make to tag multiple items

    ReplyDelete
  30. madam your asp.net version is quite outstanding ..... But

    /*
    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;

    ReplyDelete
  31. 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 ?
    Response.Write("" + name_title + "");

    ReplyDelete
    Replies
    1. Please check the path of the following file. It shows a not found error. http://www.mipectower.com.vn/ShopList.aspxSearch.ashx.

      My suggestion will be to use a absolute path. Because with url rewrite, the relative paths may not work well.

      Delete
    2. 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.

      Delete
  32. To do that probably i will have to access your code.

    ReplyDelete
    Replies
    1. can u give me your email address? i'll send u.

      Delete
  33. I just fix this problem. Thanks :)

    ReplyDelete
  34. hi 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
    Replies
    1. @yes. even i'm facing the same issue. I will publish a new version by solving the issue soon.

      Delete
    2. Today I released a new version of this search script. Hope, this address your issue.
      http://www.2lessons.info/2013/05/jsearch-free-facebook-type-search.html

      Delete
  35. 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?

    ReplyDelete
  36. Wondегful blog! I found it while surfing arounԁ
    on 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

    ReplyDelete
  37. Hello Ma;am
    Please let me know how to pass user id with user name?
    Thank you

    ReplyDelete
    Replies
    1. Use uid as "div-uid". Then while clicking the perticular div pass the uid as required.

      Delete
    2. Today I released a new version of this search script with more refinements and keyboard navigation support.

      Delete
  38. Hello Maam,

    I just need one solution that search should give result alphabatecally. I mean if i type "n" then name starting from "n" should only display

    ReplyDelete
    Replies
    1. This is quite simple. You only need to change the search.php. Replace the line-6 with the following
      $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

      Delete
  39. Simply superb tutorial..very nice blog....

    ReplyDelete
  40. Hello Madam , can i do this search option in Python, if yes then where i need to change the code.

    I try to do that in python, and i completed in different way, it is working but major problem is that it is to to slow, please make me clear , how can i make my search fast.
    I Used MongoDB having 3 lakhs of record for searching

    ReplyDelete
    Replies
    1. Yes i agree, the script is too slow. I'm working on it. Will get back to you soon.

      Delete
    2. Updated the script. Its much faster now. Please browse the new version @ http://www.2lessons.info/2013/05/how-to-create-facebook-type-search.html

      Delete
  41. Wonderful, I did not expect that the given code is accurately work… Thank u once again…

    ReplyDelete
    Replies
    1. Welcome. I always try to verify each post and also try to trim it simple, before posting.

      Delete
    2. You may find the Version 2 of this search sctipt. It is faster and has a better user interface.

      New Version of Search autocomplete

      Delete
  42. Hello Maam,
    Its wonderful,working fine upto displaying results.How to implement up and down arrow key ,enter key events in your code.I am new to jquery can you please help me..Thanks in advance..

    ReplyDelete
    Replies
    1. You may find the Version 2.0 of this search sctipt. It implements keyboard navigation and also its faster and has a better user interface.

      Search Autocomplete V2.0

      Delete
  43. hi there! - it is displaying result properly but when i click on the results it is not coming on the search box, i haven't change anything in javascript, thanks in advance

    ReplyDelete
    Replies
    1. Hi,
      I just upgraded the search and added some more features with some quick fix.

      Please feel free to check out

      Facebook type search V2

      Delete
    2. thanks version 2 is really good tutorial - i am a newbie in this field, i want to learn jquery & ajax - can you please tell me where to learn from scratch. again Thanks in advance

      Delete
    3. also can you please tell me that your code is free to use or there is any type of condition?

      Delete
  44. did you have any tutorial like facebox, where onclick it call a function in script & then open a url just like facebox - please tell me if you want more details - or should i mail you the details
    thanks in adavance
    arpit

    ReplyDelete
    Replies
    1. Hello madam! did you have any facebox like tutorial? please reply
      thanks

      Delete
  45. Hello Mam,,
    Nice tutorial , but can u help me further, yup, Im very much newbie to development & I dont know how to get data from two tables for this auto suggest tutorial.. So please help me out.. Thanks in advance...

    ReplyDelete
  46. Thank you for your great tutorial!
    I would like to add a "submit" button, so the search results will be displayed below the search box. Could you please help me with that? many thanks...

    ReplyDelete
  47. this one is great

    ReplyDelete
  48. Why you are coping ideas from 9lessons.info? you suck & cheap

    www.9lessons.info/2009/06/autosuggestion-with-jquery-ajax-and-php.html

    ReplyDelete
  49. Dear Mam ....
    Great work. nice explanations. I am worked for in this tutorial. Nice output can be appeared. Thanks for sharing this information.
    http://www.dreamdestinations.in/

    ReplyDelete
  50. Really helpful madam. Very helpful for in this information.
    Thanks for posting. http://www.dreamdestinations.in/

    ReplyDelete
  51. What if you click click the search result? what will happen? what action will it perform? can anyone answer?

    ReplyDelete