Autocomplete search using php, mysql and ajax | 2my4edge

01 August 2013

Autocomplete search using php, mysql and ajax

We know what is autocomplete in input type, that is make some predefined entered texts come under the input type box, while focusing on the input type, similarly we are searching some content from mysql database, this actually facebook style search concept to suggest some data for select before we get the exact search, for that we are using this kind of search, and this is very simple to make search in php, mysql with ajax and jquery. let see it in brief.
autocomplete search with php mysql and ajax

DOWNLOAD         LIVE DEMO

as like you see in the above image, the search will be comes like that by using php, mysql and ajax with jquery.

DATABASE DETAILS

database name-->2my4edge
table name --> autocomplete
column names --> id, name, email

DB.PHP
<?php
$connection = mysql_connect('localhost','root','') or die(mysql_error());
$database = mysql_select_db('2my4edge') or die(mysql_error());
?>

the above is database file.

INDEX.PHP
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search for people" />&nbsp; &nbsp; Ex:arunkumar, shanmu, vicky<br /> 
<div id="result"></div>
</div>
just give this input type only in index page with AJAX. you can see the ajax coding below here that is also comes in index page

AJAX
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;    
});

jQuery("#result").live("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find('.name').html();
    var decoded = $("<div/>").html($name).text();
    $('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});
$('#searchid').click(function(){
    jQuery("#result").fadeIn();
});
});
</script>
the above all for make action in SEARCH page with out refreshing the page.

SEARCH.PHP
<?php
include('db.php');
if($_POST)
{
$q=$_POST['search'];
$sql_res=mysql_query("select id,name,email from autocomplete where name like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['name'];
$email=$row['email'];
$b_username='<strong>'.$q.'</strong>';
$b_email='<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="show" align="left">
<img src="author.PNG" 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/>
</div>
<?php
}
}
?>
that's it. as like the usual fetch from database with like and here we are just adding str_ireplace, that's it. and other thinks are as like we know, that is very simple one. let's try this. and each of our entering text that wil comes as in strong letter.




RELATED POSTS:








124 comments:

  1. thanks thats all i need, you are the best

    ReplyDelete
  2. It seems to be a bug.

    When you search, and click on the image or text, it will not be selected. You have to click in the "white" area.

    ReplyDelete
  3. Antoher bug is that it is case senestive.

    If you search for "a", all "a" will be small in the search output. If you search for "A", all "a" will be in capital.

    How to fix?

    Is there anyway your could combine this with http://www.w3schools.com/php/php_ajax_database.asp?

    ReplyDelete
  4. what for 6 different table suggestion like fb users group pages ext

    ReplyDelete
  5. Any solution for this?

    "When you search, and click on the image or text, it will not be selected. You have to click in the "white" area."

    ReplyDelete
  6. Hi, thanks for the excellent tutorial. I have configured this so that when an item is selected from the drop down box, it updates the input box and then a Submit button can be used to direct you to a specific URL. This works fine but its very temperamental and doesnt always update the input box straight away. Ideally, I would like the selection from the drop down box to automatically direct you to the URL rather than the user having to click on the Submit button as well. Any suggestions? Is this a tweak to the JQuery?

    ReplyDelete
    Replies
    1. where can i put php codes of search

      Delete
  7. When I start typing I just get

    '.$q."; $final_username=str_ireplace($q, $b_username, $username);
    $final_email=str_ireplace($q, $b_email, $email);?>

    Am I doing something wrong? I am on IE11 if there is an incompatibility with that?

    ReplyDelete
  8. Works like a charm! I only have one problem, that is if i click the input off focus, the current search results (in the #result) do not disappear. Anyone know what that is?

    ReplyDelete
    Replies
    1. if(searchid!='')
      {
      $.ajax({
      type: "POST",
      url: "search.php",
      data: dataString,
      cache: false,
      success: function(html)
      {
      $("#result").html(html).show();
      }
      });
      }
      else
      {
      $("#result").hide();
      }

      Delete
  9. my results doesnt want to disapear

    ReplyDelete
    Replies
    1. if(searchid!='')
      {
      $.ajax({
      type: "POST",
      url: "search.php",
      data: dataString,
      cache: false,
      success: function(html)
      {
      $("#result").html(html).show();
      }
      });
      }
      else
      {
      $("#result").hide();
      }

      Delete
    2. i want to search through ajax all field of data base like search by name, search by number, search by area anything user want to search.
      if you have any idea or any code please contact me to below email address
      skunjadiya222@gmail.com

      Delete
  10. Obrigado ajudou-me bastante ...continue assim

    ReplyDelete
  11. I have the same problem with others, any solutions?

    "When you search, and click on the image or text, it will not be selected. You have to click in the "white" area."

    ReplyDelete
  12. thank yooooooou

    ReplyDelete
  13. yes is working nice and thankyou so mush great work

    ReplyDelete
  14. For those having difficulties with clicking, edit it to make the result div clickable. thatll sort your problem out

    ReplyDelete
  15. Awesome! Cheers

    ReplyDelete
  16. It's working...nice....thank you...

    ReplyDelete
  17. ur a saver man

    ReplyDelete
  18. For those having difficulties with clicking, edit it to make the result div clickable. thatll sort your problem out. Please how

    ReplyDelete
  19. Ugh, a coding blog that doesn't accept HTML inside a comment? That's awful.

    I'll do my best then -

    Replace the "jQuery("#result").live("click",function(e)" function with:

    jQuery(".show").live("click",function(e){
    $name = $('span.name', this).html();
    var decoded = $("LEFTBRACKETdiv/RIGHTBRACKET").html($name).text();
    $('#searchid').val(decoded);
    });


    Works for me. Can click anywhere in it and it works.

    ReplyDelete
    Replies
    1. its not working

      Delete
    2. Put onclick='fill("")' within div tag. and you don't need span tag.

      Delete
  20. added a column `link` to mysql and search.php, how to make the the search results clickable to go to the corresponding link? ie on click first result, go to google.com?

    ReplyDelete
  21. Hi
    http://www.discussdesk.com/autocomplete-search-in-php-mysql-json-with-navigation.htm

    ReplyDelete
  22. Any solution for this?

    "When you search, and click on the image or text, it will not be selected. You have to click in the "white" area."

    ReplyDelete
  23. Works great and I have adapted it to suite my needs.

    BUT - I have noticed the script conflicts with bootstraps Modal Fade. When the script is on the bage the fade no longer works.

    Any ideas?

    ReplyDelete
  24. It's working fine thank you so much...

    ReplyDelete
  25. This doesn't work for me in IE 11.
    Works fine in FF 28 and Chrome 34.

    I say "fine" lightly. I too have issues with clicking within the result div, sometimes it doesn't work. I applied the suggestion made by Rob Whit and I can click anywhere, thank you!

    IE support would be great, though.

    ReplyDelete
    Replies
    1. why mine couldnt work? can you help me with this plssss.

      Delete
  26. Very helpfull, thanks, there another example, it may help you:
    http://www.bewebdeveloper.com/tutorial-about-autocomplete-using-php-mysql-and-jquery

    ReplyDelete
  27. Thanks for share. Nice tutorial :)

    ReplyDelete
  28. Hi, Nice working example

    ReplyDelete
  29. Cool simple nice working example. Thanks You very much

    ReplyDelete
  30. One of the problems you may be having is if you are loading a newer version of jquery. If you are using anything later than 1.9 then the .live() function will not work for you. You need to change the .live() in the javascript to .on()

    The new working JS would be:

    ...

    jQuery("#result").on("click",function(e){ ...

    jQuery(document).on("click", function(e) { ...

    ...

    Hope that helps someone looking at this now.

    ReplyDelete
    Replies
    1. That worked for me!!! thanks

      Delete
    2. thank you

      Delete
  31. you for got to add the Css - Pretty important in the tutorial

    ReplyDelete
  32. Thank you.

    ReplyDelete
  33. Nice injection vulnerability LOL

    ReplyDelete
  34. Arun rocks. Thanks.
    Ebonywiz

    ReplyDelete
  35. Amazing! Very beautiful e useful auto-complete functionality. I have just one question. Are there any way to navigate with this options by keys up and down from keyboard?

    ReplyDelete
  36. Is there any way to navigate suggestions with up and down arrows from keyboard?

    ReplyDelete
  37. Yes, its very beautiful but has some bug.
    When i click on text(name of people) or photo too, it is not select..
    Please fix dis issue. Otherwise its very preety to see.. Thanx

    ReplyDelete
  38. Totaly works! thank u very much.. you are the best! :D

    ReplyDelete
  39. Yes, its very beautiful but has some bug.
    When i click on text(name of people) or photo too, it is not select..
    Please fix dis issue. Otherwise its very preety to see.. Thanx

    ReplyDelete
  40. total solution auto complete is:- http://phpseason.wordpress.com/2013/02/13/php-autocomplete-tutorial-using-jquery/

    ReplyDelete
  41. I have made such 2 search boxes and 1st box copies the values of the other box . . . . . what to do plzz help

    ReplyDelete
  42. when i clicking on image its not working

    ReplyDelete
  43. where i have to place the ajax code

    ReplyDelete
  44. hi bro, while approving the comment, why don't suggest a solution as it's not a big question to you

    ReplyDelete
  45. thanks i really need this :3

    ReplyDelete
  46. Thanks, now i can make my own autocomplete search fiture.

    ReplyDelete
  47. Very fantastic code. Thanks for your wonderful work.
    But there small problem here, when the search list is too long, could web make a scroll bar and limit results to 5 or 6?

    ReplyDelete
    Replies
    1. I did it, just insert a div with style "height: 300px; overflow-y: auto;" (the dimension is up to you).
      I don't know how to post the whole code here, just contact me as skype kazihaha

      Delete
  48. How can I change the script to pick the email instead of the name for the input field?

    Great work though! :)

    ReplyDelete
  49. use "$username" instead of "$final_username" in div tag

    and remove "name like '%$q%' or"

    in search.php file

    ReplyDelete
    Replies
    1. Hi,

      I ended up adding class="email" on the div in search.php and changed the ".name" to ".email" on the ajax code in index.php.

      That did the trick. Thanks!

      Delete
  50. Please help me.
    How can we align the div result at right of input box?

    ReplyDelete
  51. "that is also comes"? Go back to school, ffs.

    ReplyDelete
  52. Thank you. Really it is nice.

    ReplyDelete
  53. should be trying, it is vey help for us

    ReplyDelete
  54. Hi anyone fixed the issues yet?

    1. "When you search, and click on the image or text, it will not be selected. You have to click in the "white" area."

    and the text box needs to be populated too...

    ReplyDelete
    Replies
    1. Use the below

      $("#result").on("click",function(e){
      $name = $('span.name', this).html();
      var decoded = $("leftarrowdiv/rightarrow").html($name).text();
      $('#searchid').val(decoded);

      });

      instead of

      jQuery("#result").live("click",function(e){
      var $clicked = $(e.target);
      var $name = $clicked.find('.name').html();
      var decoded = $("leftarrowdiv/rightarrow").html($name).text();
      $('#searchid').val(decoded);
      });

      Delete
    2. on instead of live never seems to work with latest 1.9 jquery. it always shows the first result in div "show" even if i click the first and the second result in show div

      Delete
    3. on instead of live never seems to work with latest 1.9 jquery. it always shows the first result in div "show" even if i click the first and the second result in show div

      Delete
  55. Hi everyone,

    How can i get the selected image or text value to appear on the text field ?

    Thanks

    ReplyDelete
  56. hello everyone...
    how can i insert or select togather img and text and echo same div and if i wanna only text then echo only text and if only img then only img echo ?
    so please any idea

    ReplyDelete
  57. how can i insert or select togather img and text and echo same div and if i wanna only text then echo only text and if only img then only img echo ?
    so please any idea

    ReplyDelete
  58. have liked me so much !
    Gracias

    ReplyDelete
  59. hi everyone !
    i tried this script and it's i need.
    but there is a function which is not present : the multiple search with unordered words.
    I explain myself :
    in the Database i have for example : " hello world, my name is john"
    if i search "hello world", i will find it
    but if i search "world hello" i will NOT find it

    Someone has a solution for this problem ?
    It'll be great !

    Thanks a lot

    ReplyDelete
  60. I cant pic the item from this list how could i do that!

    ReplyDelete
  61. good tutorial very helpful another good tutorial to create search system using php and mysql http://talkerscode.com/webtricks/basic-instant-fulltext-search-system-using-ajax-and-php.php

    ReplyDelete
  62. Nice script, but unfortunately it does not work on iPad. Cannot pick the item from the result list.

    ReplyDelete
  63. This is extremely helpful. Thanks man!

    ReplyDelete
  64. Does anybody know if there is a way to do this without JQuery???

    ReplyDelete
  65. Yes that is work.
    Can apply in my web
    Thanks man..!

    ReplyDelete
  66. Does anybody know if there is a way to do this without JQuery???
    bantal mobil

    ReplyDelete
  67. How to auto submit on clicking the autocomplete result.
    mail me the answer please at mukesh.jangid55@gmail.com

    ReplyDelete
  68. Big thanks for mr Arunkumar
    Very benefit for me.

    ReplyDelete
  69. Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in ...in search.php line no. 7 i'm getting this error..

    ReplyDelete
  70. Great auto complete search, is there a option to show that there are no results in the database that match the input?

    ReplyDelete
  71. really great sharing, thank you guy

    ReplyDelete
  72. Is it possible to view a text when no search results are found?

    ReplyDelete
  73. Is it possible to view a comment when no results are found in the database?

    ReplyDelete
  74. I want to select the names in the DIV tag to be selected using the keyboard up and down arrow. Can anyone please help me out from this ? :(

    ReplyDelete
  75. Hello

    Nice example , but how to make the example responsive for all the screens ?

    Regards

    ReplyDelete
  76. thanks,great example kumar

    ReplyDelete
  77. your wonderful friend..youve been my helper

    ReplyDelete
  78. Thank You........!!

    ReplyDelete
  79. For the white space clicking problem, I found this useful:

    if($(e.target).attr('class') == 'show')
    {
    var $clicked = $(e.target);
    }
    else
    {
    var $clicked = $(e.target).parent();
    }

    ReplyDelete
  80. For the white space clicking prob, I found this useful:

    if($(e.target).attr('class') == 'show')
    {
    var $clicked = $(e.target);
    }
    else
    {
    var $clicked = $(e.target).parent();
    }

    ReplyDelete
  81. Thanks a lot brother.very helpful..

    ReplyDelete
  82. Thanks a lot.Very useful script.


    .....

    ReplyDelete
  83. thank you vry much i have wasted around 4 hrs finally got thanks

    ReplyDelete
  84. Hello
    I would like to know how to click on the result to display the choice, thanks

    ReplyDelete
  85. Thanks friend,
    it really helped me....

    ReplyDelete
  86. Could you create this with CodeIgniter 3?

    ReplyDelete

^