Ajax Search Box PHP

Ajax Search Box in PHP and MySQL

In this tutorial we are going to Build Ajax Search Box using PHP as core language. Ajax Search booms the usage of web projects such as one Google uses. Searching through Ajax and also maintaining less load on Server is big challenge.

LIVE DEMO DOWNLOAD

I have already posted about Ajax Search Box in Node, we are replacing Node back-end script with PHP. Format of data coming from Server is JSON itself. We will call the Search web service using GET request.

Database Design:

Open up your PHPMyadmin and create database of any name. Inside that database execute following query.

CREATE TABLE 'user_name'
(
    user_id INT(20) PRIMARY KEY,
    first_name TEXT
);

Put some dummy data in it using INSERT command.

Designing Front-end :

I am using Twitter typeahead JavaScript library to perform Ajax call to PHP file. It’s neat and clean library specially designed for this kind of purpose. Just add the path to HEAD section and you are good to go.

index.html
<html>
  <head>
    <title>Ajax Search Box using PHP and MySQL</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">        </script>
     <script src="typeahead.min.js"></script>
    </head>
    <body>
     <input type="text" name="typeahead">
    </body>
    </html>

In above code we have designed the front-end of our app. CSS codes are available in Download package.

Calling PHP Script Using GET

Next task is to call our PHP script when user type in the text box. Since we are doing this using typeahead library we can do this using following.

index.html
  <script>
    $(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'typeahead',
        remote:'search.php?key=%QUERY',
        limit : 10
    });
});
    </script>

It automatically fetch text box value in %QUERY variable.

Retrieving data from MySQL and returning as JSON:

Here goes main task. In PHP file first we have to fetch the GET value which stored the search parameter. Then we have to form a connection to MySQL database and fire query to get relevant result.

Once the result is been fetch, we have to pack it in JSON format and return back to front-end to display it as result.

search.php
<?php
    $key=$_GET['key'];
    $array = array();
    $con=mysql_connect("localhost","root","");
    $db=mysql_select_db("database name",$con);
    $query=mysql_query("select * from table_name where <coloumn_name> LIKE '%{$key}%'");
    while($row=mysql_fetch_assoc($query))
    {
      $array[] = $row['title'];
    }
    echo json_encode($array);
?>

Kindly change the parameter according to your database and column details.

Running the code :

If you have downloaded the project source code, then create database of any name and table using code shown above and simply update those information in Search.php

Place the project folder in ‘htdocs‘ directory and access it using localhost/foldername.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

232 Comments

        1. Get all the data of railway time table, categorise them and insert them in MySQL table. Writing php script to connect to database and show all those records on HTML page using good CSS.

      1. need a help.I used this for a project.and it works fine.I want to use it for multiple pages.so I wrote is separately and used angularjs to add it to needed pages.

        when I use this tag and use it,it will not work.can you give me a solution?

  1. no that is not the tag.I used ng-include=”pathtofile.php” in a div tag to include it in needed pages.But it is not working

  2. hey i’m trying to implement ajax search by using your code but failing with fetching data from data base

  3. even i say thousand of thanks,it will not sufficient at all.. i was searching this for a long time! but not a single 1 was running correctly! Finally Your work saves me from getting supple in the exam!!
    I have no words to thank you! wish U a vry Hppy life.. M grtfl To U.

      1. Hello! Again I need Your help ….
        I have a database with 3 diffrnt tabls.. I want a singl search for every column in the database.
        will You help me to sort out ths prblm?

          1. Hi ,

            i need a help from you.. i need a search like facebook and need to insert their id to another table..

            search names from a table and insert their id to another table…

          2. Assuming ID is there on table you are searching. You can select those rows and once the search is complete you can fetch the ID of each row and INSERT in another. Where you are stuck ?

          3. Hi! First of all thank you very much for taking your time and effort sharing your knowledge with ours.
            I would like to learn how to build a blog using php mad MySQL
            Have you done a tutori like this one before or do you have any source code please.
            Kind regards

  4. am working on my music lyrics website php front and mysql back end, i wanna use one search box to extract tracks,genres,artists,lyrics,group etc hope u understand me well,any help in php script i welcome it.thanks

    1. If you are sending type from Front-end such as lyrics,groups etc then in PHP script.

      <?php
              $type=$_POST['type'];
              $query=mysqli_query("SELECT * from YOUR TABLE where type='$type' LIMIT 10");
              while(mysqli_fetch_row($query){
                      //put it in array or type you want and send it back
              });
      ?>

      Or if you wanna search whole DB according to single input then as i explained in post. Fire query to DB and return it back. Let me know if you need more help.

  5. Hi!

    This code is very neat!

    I have a database with multiple columns. How can i make it search from 3 columns instead of only one?

    i have: Phone brand, phone model, phone variant.

    So, for example i have
    (Sony) (Xperia Z3) (16GB)
    (Sony) Xperia Z2) (16GB)

    How can i modify the code so I can search for Sony it will show both phones but if I search for Xperia Z2 it will show only one result?

    Thanks!

    1. Assuming SONY is in brand_name column, Xperia is in phone_name column and 16GB is in capacity column. Query will be like this.

      $query=mysql_query("select * from table_name where brand_name,phone_name,capactiy LIKE '%{$key}%'");
      1. Thanks! I got it! Now if I want to make each result a link, how can I do it without displaying part of the source code after you click on the result? I programmed it like this:

        while($row=mysql_fetch_assoc($query))
        {
        $array[] = ” . $row[‘completename’]; . ”
        }
        echo json_encode($array);
        ?>

        It does work but when I click on the result, it shows the <a href… part on the text box before loading. Is there any way of hiding it?

        Thanks!

        1. To hide that, use click event listener in jQuery and use preventdefault() to actually redirect it, then fetch href value using .attr and redirect the page to that value which is address clicked by user. Hope that helps.

          1. Hi, that didn’t really work out for me. I am seriously new at this. But how do I get an image on the main page below (from blob mysql table) once I confirm my selection in the search box??

          2. Doesn’t work, please elaborate on this.
            my code is as follows:
            $name_query=mysql_query(“select ID,name from list where `name` LIKE ‘%{$key}%'”);
            while($row=mysql_fetch_assoc($name_query))
            {
            $id = $row[‘ID’];
            $username = $row[‘name’];
            $array[] = “Username: ” . $username . ““;
            }

            gives me a link in the dropdown, but how to have a listener 🙁

  6. This is an excellent tutorial/script. I have everything working and I am able to search my desired query. Forgive my ignorance, but I’m not sure how to utilize the data once I have selected the desired record. Can you use the input field as part of a form to enter the selected record into another table? Hope that makes sense. Thanks again.

  7. please i need a quick response, i need to search through multiple tables in my database using just one command line. i tried

    $perform_query=”SELECT * FROM apple_tv,cam_coder,category,core_network,document_cam,i_pad,macbook,mac_mini,monitors,projector,still_cam,windows_devices WHERE bar_code LIKE ‘%$search%’OR username LIKE ‘%$search%’ OR system_name LIKE ‘%$search%’OR serial_number LIKE ‘%$search%’ ORDER BY grade DESC “;

    but i get this error “where clause is ambiguous”. is there any other way i can search through all the tables in my database? URGENT

  8. Hi,

    I tried this on IIS 7.5 but can’t figure out why it doesn’t work.
    Do you know if there is something else to do ?

  9. A few people have asked how to add multiple form fields and search to separate databases.

    You can create 2 search files checking different databases/tables etc.
    so search.php and search2.php

    Then put this into the head of the page you have your form on replacing the “name of person” with what ever the name of 1 of your form field is and do the same for “city” to what ever other form field you want to search for.

    $(document).ready(function(){
    $(‘input.nameofperson’).typeahead({
    name: ‘nameofperson’,
    remote:’search.php?key=%QUERY’,
    limit : 10
    });
    $(‘input.city’).typeahead({
    name: ‘city’,
    remote:’search2.php?key=%QUERY’,
    limit : 10
    });
    });

    now make sure that the “name” and the “class” for each form field match 1 of the above.

    and for the second field:

    Hope this helps and makes sense to anyone 🙂

    1. Hey Stoogle, Thanks for that extra information, it was what i needed to get this working!
      I have one extra tip for people that want to use thit also. You don’t need to use 2 remote search scripts. If you add an additional get variable to it you can put all your search queries in 1 php file.
      Fi:
      1st part: remote:’search.php?do=nameofperson&key=%QUERY’,
      2nd part: remote:’search.php?do=city&key=%QUERY’,

      And then in the search.php file you add something like:

      if ($_GET[‘do’]==’nameofperson’) {query1}
      elseif if ($_GET[‘do’]==’city’) {query2}

      1. Hi Shahid,

        Your piece of code is very helpful! I have been able to use the basic functionality here. I want to take it further with the result itself pointing to a hyperlink, and it did work.

        The catch here is, if the user selects the text instead of clicking the hyperlink it fills in complete tag in the field, can you please suggest.

        My code so far is as follows:

            $name_query=mysql_query("select ID,name from list where `name` LIKE '%{$key}%'");
            while($row=mysql_fetch_assoc($name_query))
            {
              $id = $row['ID'];
              $username = $row['name'];
              $array[] = "<a href='listing.php?id=" . $id ."' rel="nofollow">Username:"  . $username . "</a>";
            }
            echo json_encode($array);

  10. I’m using this tool on a website and got it working great. I’ve embedded it within a form but the value isn’t being passed onto the POST page of my form. Can you advise?

    Note that I’m using multiple search boxes (24 to be exact) on the form, all of them are searching fine and they’ve all been given unique names. But the values will not pass on to the next page.

  11. Nice code sir. 🙂 I need a little help. I need to get multiple database values . Say for example i select a certain item in the live search and assuming it has a corresponding id in database, so whenever i select the certain name its it will be save in a hidden input type. How can i achieve that ? THanks 🙂

    1. Return the ID or whatever element you want from DB to front-end foreach names and store those ID in hidden element or HREF in anchor tag, on click you can retrieve the hidden value. Hope it helps.

      1. Hi Sir, I don’t get it. For example , if I try to retrieve ID and name from my db using a query, but only want to show the name in the result and hide the ID to retrieve the correspondig once you have selected a name in the live search. How can I do it?

  12. Hi,

    Thx, got it up running in a few minutes.
    I did not like the placeholder not going away when focus is on the input field.
    So i made the next adjustment :

    input type=”text” name=search class=”typeahead tt-query” autocomplete=”off” spellcheck=”false” placeholder=”hi there” onfocus=this.placeholder=” value=”” onblur=”if (this.placeholder == ”) { this.placeholder = ‘Hi there’;}”

  13. Fantastic and simple bit of code – thank you, however I have the query set to show the search of column A in a table, but I want to also show the related data in column B in a separate box once chosen from the drop down list.

    Each time I try to add this additional code the whole scripts stops working, so I’m not sure what code I should be adding and where!

    I have a limited knowledge of php & html so an example would be really helpful!

    1. If you want to achieve this i think you need to call different PHP file which returns the values from DB related to option selected. So use jQuery to fetch the select box value and call php file in that run SELECT query to retrieve values from table and populate them in another element using jQuery itself.

      1. I have inserted this code in the script after the already existing function, and added an alert to show the selected value, but it didn’t work ! 🙁 :S

      2. i have done go button next to search and i am searching product name and want when i search and select product name and click go button , product detail to show without page refresh.how should i do

  14. Mine says the typeahead doesn’t have method..
    Uncaught TypeError: Object [object Object] has no method ‘typeahead’

  15. sir I have three questions
    (I am sorry in advance if I am being silly cuz I am new )

    1. If I select the Id from this field and want to automatically add the corresponding name in the next field.How can i do that?

    2. {$query=mysql_query(“select * from table_name where LIKE ‘%{$key}%'”); }
    could we search from two columns like search from id & name columns?

    3. How could I show the name in arabic in the search box. currently it shows ????????????

    1. 1: You can do select to name field as well in SQL query along with ID. For each row there is ID and Name you can then associate it.
      2: You can use OR , AND query to search for more then coloumns.
      3: I am not sure about arabic. Apology.

  16. sorry i repeated one of the questions, I would like to know about the rest of the questions.
    1. I am using it in a form for id and name. what I would like to do is If I write the id Then it automatically adds the name in the next field.

    2 I would like to know how to make it multi lingual support. How to show the arabic data in the search box currently it is showing ??????????

    Thanks a lot for your code. May you have a wonderful Life filled with lots of fun.

    1. 1: You need to either call SQL query again with reference to ID or store the Data returned by search in some variable and use it in Form.
      2: Multilangual is something i need to figure out yet. As a suggestion please have a look at MySQL language support. You may get some idea.

  17. Why its a little bit delay,
    when the first time i search query for “a” its a little bit delay.
    is it cause by the connection my internet? or there’s something miss.
    cmiiw.

  18. Notice: Undefined index: id in C:xampphtdocsmclibrarysearch3.php on line 2

    Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:xampphtdocsmclibrarysearch3.php on line 7
    []

    What are the problems here??? 🙁

    1. Hi Rowel,
      This error comes up when SELECT query failed ! Are you sure you are putting right name of database along with i guess you changed the file name too, make sure you reflect the changes where it is required.

  19. Hi,

    It a nice tutorial that gives wonderful direction.

    Have query if you can help out with:
    There is a attribute in my form that uses typeahead and populate values from the database. However, the attribute should have a feature where it can be added by the user as many times as wanted i.e. multiple rows. In the API I have provided an option using JQUERY where new rows can be added in the table pertaining to this particular field. The query goes like this:

    $(document).ready(function()
    {
    var cnt = 4;
    $(“#anc_add”).click(function()
    {
    $(‘#tbl1 tr’).last().after(‘QUICK ONTOLOGY SEARCH ‘);
    cnt++;
    });

    $(“#anc_rem”).click(function()
    {
    if($(‘#tbl1 tr’).size()>3){
    $(‘#tbl1 tr:last-child’).remove();
    }
    else
    {
    alert(‘Atleast one annotation is required’);
    }
    });

    });

    This script is working fine but the typeahead script is not working for the newly added rows. Any idea how this can be resolved.

    1. Some part of the script was missing:

      $(document).ready(function()
      {
      var cnt = 4;
      $(“#anc_add”).click(function()
      {
      $(‘#tbl1 tr’).last().after(‘QUICK ONTOLOGY SEARCH’);
      cnt++;
      });

      $(“#anc_rem”).click(function()
      {
      if($(‘#tbl1 tr’).size()>3){
      $(‘#tbl1 tr:last-child’).remove();
      }
      else
      {
      alert(‘Atleast one annotation is required’);
      }
      });

      });
      </script

  20. Hi Shahid,

    I need some help.

    I have website that displays bus route and bus stop names. I need to make these routes and bus stop names as link to make them click-able. For example, I have route no 56. If anyone click on 56 then it will open a other second page. Here, I have to pass on this variable (56) to other page. At present, I pass this variable thorough URL (example second page http://www.example.com/routedisplay.php?routeno=56) and get this variable on second page by GET command.

    But I want to remove question mark and make it clean URL (such as http://www.example.com/route/56). How to get this? I tried to create route folder and put a index.php file there to process but nothing works.

    Please help, I am trying to find the solution for many days.

  21. How would you get this to work on a php file? my website is in php but when I use the same code that works in a html file it does not work. So there must be a method to integrate this into a php file.

  22. I figured it out, for some reason the ajax call was not working because of masonry. The solution was to make the ajax call and declare typeahead.min after masonry.

  23. It works great!

    But I downloaded the latest version of typeahead (0.11.1). But the code no longer works. What changes must be made to the code to work with the latest version?

    Thanks

  24. great work, I want to fetch these record below in a table by selecting item in a number of list, please help me.

  25. Hi,
    Great project. However, I need a bit of assistance.
    How can I add the live search result to a textbox. I dont want it to hyperlink.

    Thank you.

  26. Hi!
    First of all thank you for sharing this code.
    How can I display the hole db-row in one line and not just one attribute of it?

  27. This tutorial is great you have save me with my time but need little a help here i’m using this to search in inventory management system so, i’m using it for search items for each item there is db fields called project name, category, sub category so i need to filter the search results according to those columns in the database, i’m selecting those fields earlier page and passing to current page by post method.
    please help me on this it’s very important to me

    tahnks

  28. I want to ad the returned value from the query to an anchor tag which will send it to another page using a GET request, but when i concatenate the value from the json it won’t work, any solution in mind? Thanks in advance 🙂

  29. Hi, Nice tutorial.

    I need to search three fields.

    My query is
    $query=mysql_query(“select * from users where fname, lname, email LIKE ‘%{$key}%'”);
    while($row=mysql_fetch_assoc($query))
    {
    $array[] = $row[‘fname’];
    $array[] = $row[‘lname’];
    $array[] = $row[’email’];
    }

    Is this correct???
    I need correct query brother..! After click on that name or email it will go to separate page. How can i give href link??

  30. Hi Bro,

    I need search two fields like fname, lname and email.
    $query=mysql_query(“select * from users where fname, lname, email LIKE ‘%{$key}%'”);
    while($row=mysql_fetch_assoc($query))
    {
    $array[] = $row[‘fname’];
    $array[] = $row[‘lname’];
    $array[] = $row[’email’];
    }

    It is not working, please correct my code. And i need to give href link for search result. How can i give href link in search output?

    1. $query=mysql_query(“select * from users where fname OR lname OR email LIKE ‘%{$key}%’”);
      while($row=mysql_fetch_assoc($query))
      {
      $array[] = $row[‘fname’];
      $array[] = $row[‘lname’];
      $array[] = $row[’email’];
      }

  31. Hi shaikh,
    How can i fetch images from other table for search?
    could you please explain in code.

    $sql=mysql_query(“select * from profile where name LIKE ‘%{$key}%'”);
    while($res=mysql_fetch_assoc($sql))
    {
    $img_qry = mysql_query(‘SELECT * FROM user_profile WHERE user_id =’.$res[‘id’]);
    $rslt = mysql_fetch_array($img_qry);
    $array[] = $res[‘fname’];
    $array[] = $rslt[‘img’];
    }

    Is anything wrong in this code? Please fix this issue shaikh.

    1. Hi Bhuvi,

      Please use join instead of two query. I can see you are fetching user information and profile information form different. Write query like this.

      $sql = mysql_query("SELECT * FROM profile INNER JOIN user_profile ON profile.user_id = user_profile.user_id");

      $ res = mysql_fetch_assoc($sql);

      // You should get every info like fname, img in $res variable.
      1. Hi sheikh, It is not more working. It does not display anything like Images, names. Would you send me the whole file changes.

  32. Good day great person,

    When an example like this:

    $query=mysql_query(“select * from users where fname OR lname OR email LIKE ‘%{$key}%’”);
    while($row=mysql_fetch_assoc($query))
    {
    $array[] = $row[‘fname’];
    $array[] = $row[‘lname’];
    $array[] = $row[’email’];
    }

    As a result I get all of the possible search items by typing whatever in the search box.
    Help pease!

  33. hai your work is great…. but i have some doubts can you help me please…. reply me…. the problem is using search box in html i have to get data from single coloum name

    1. Hello Shahid,
      First of all, I love how easy this tutorial is compared to anything else I have found out there. I am however having a small issue. When I type into the input, no response appears. I used your exact code and simple changed the search.php to fit my needs. I have already verified that it is not an issue with my connection to the database as when I go to search.php, all my rows appear. This is my log file if it provides any insights:
      WEBSITE – – [28/Dec/2015:07:02:25 +0000] “GET /search/search.php?key=barbie HTTP/1.1” 200 221 “http://——-/search/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0”
      WEBSITE – – [28/Dec/2015:07:07:30 +0000] “GET /search/search.php?key=barbi HTTP/1.1” 200 221 “http://——–/search/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0”
      WEBSITE – – [28/Dec/2015:07:07:30 +0000] “GET /search/search.php?key=b HTTP/1.1” 200 8468 “http://——–/search/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0”

      Thanks,
      Liam

  34. Thanks brother. I have a question .. I want to pass another variable with QUERY. For example

    $(document).ready(function(){
    $(‘input.typeahead’).typeahead({
    name: ‘typeahead’,
    remote:’search.php?key=%QUERY,key2=var2′,
    limit : 10
    });
    });

    But I can not pass key2 value . Pls help me.

  35. Thanks brother. I have a question about bootstrap live search .. I want to add one more condition for search. So want to pass another javascript variable key with key. For example

    $(document).ready(function(){
    $(‘input.typeahead’).typeahead({
    name: ‘typeahead’,
    remote:’search.php?key=%QUERY,key2=var2′,
    limit : 10
    });
    });

    But I can not pass key2 . Pls help me.

  36. Hi mate!

    Thanks for a great script.
    Does it support character like åäö? Now i got a interesting error, posts containing those characters wont show at all. Everything is set to use utf8. Any ideas?

    Cheers,
    Daniel

  37. hi

    thanks for this script is very helpfull. I have one question, is there a way to add an if or validation.
    If the query found results then show the dropdown like is working right now, and if not show a “not found” text?

    thank you in advance

  38. Hi Shahid,

    Also many tnx for this example.
    The base is working but i struggle with the return data.
    In my situation i want to get back a list of data (that works) but also per data an Id which should not be visible, but
    which i can use as post data in the submit.
    I probably have to change the json array but i then i don’t know how to seperate the data in the post form and use the id as hidden id.
    To clearify my example: I have a table with strings (can be duplicate) and unique number id’s.
    I want the list to contain the strings and i want to submit with just the id.
    Additional i’d like to submit immediatly on selecting.

    gr,
    Ronald

  39. Hi Shahid,

    I have use your wonderful ajax search functionality.

    I used it to search company names and looking for small functionality if some select the company name , then it should all details from database, like address, name, contact person means whatever details is associated with that company from database.

    please let me know what to do get these results

    1. Hi Himanshu,

      Since you need dynamic data on each click i will suggest you to develop a API which accept company name as parameter and returns you all response from Database. Then you can display that info in UI wherever you wish.

      Hope it helps.

  40. Hi

    i’ve a strange situation. my db has 150000 rows, and i cant get this to work, doesnt show any result.

    If a use a smaller db (like 200 rows) it works perfectly.

    I’ve put limit : 10 and minLength:5 in the index, and limited to 10 in the sql query.

    another strange thing is that if a limite to 1 in the sql query ir works…

    what is happend ?

    many thanks

  41. Hi, I’m new with JQuery. My question is, i got this status ‘404 not found’ on domain ‘localhost’ for given URL ‘GET typehead.min.js’

  42. where on earth do i get typeahead.min.js?? i have been searching all over the web and can not find this or anything compatible with this code, i get search.php to work, but the html and typeahead will not work no matter what i do.

  43. where on earth do i get typeahead.min.js?? i have been looking all over the web to find this and have not found one compatible, i can not get typeahead to work at all.

  44. i have done everything correctly but the only thing that’s not happeniing is that the live search is not working.When i run the php page the jason_encode prints all the name there that means that it is taking data from the databse but still live search is not working.

  45. my last step is not working ie(Once the result is been fetch, we have to pack it in JSON format and return back to front-end to display it as result.)
    please help me i need to get over this problem soon.

  46. Great tutorial. One question is there some limitations with bigger database. I have got 5000 job titles in the DB but up to now I got it just working with one keyword (cust -> Customer service). Even though I have many Management Jobs “man” does not return anything ??

  47. Hey man, thanks for this. I was wondering, this code will show whatever I put in the $array[] = $row[XXX] as the result, but is there a way I could show more than that?

    E.g. It’s showing me the Course Name for a university cource, can I make it show the course code with it? Like instead of showing Accounting, it’ll show Accounting 100.

    The code is also in a column in the same table.

    Thanks.

  48. Hi I’m also looking for typeahead.min.js.
    Clicking on the link you give opens a file called typeahead.bundle.js, do I save this file as typeahead.min.js or do I change the could you please clarify.

    Thanks
    David

  49. Hi Shahid,
    Thanks very much for this, everything works fine.
    I would like to output the results as a select box,
    echo json_encode($array); at the end of search.php
    outputs a text list.
    Can you suggest how I can output this instead as an html select box.

    Thanks for your help

    David

  50. Hello Shahid,
    I was hoping you could help me with a small bug in my code. I downloaded your code and simply edited search.php to fit the specifics of my database. My issue is that I recieve no response when I type into the search box. I have already verified that the issue is not with my connection to the database because when I go to search.php, all my rows are outputted. The following is what appears in my logs if it becomes useful:

    WEBSITE – – [28/Dec/2015:07:02:25 +0000] “GET /search/search.php?key=barbie HTTP/1.1” 200 221 “http://——-/search/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0”
    WEBSITE – – [28/Dec/2015:07:07:30 +0000] “GET /search/search.php?key=barbi HTTP/1.1” 200 221 “http://———/search/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0”
    WEBSITE – – [28/Dec/2015:07:07:30 +0000] “GET /search/search.php?key=b HTTP/1.1” 200 8468 “http://——–/search/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0”

    Thanks,
    Liam

          1. Sorry, I forgot to take it out of the PHP brackets:

            $key=$_GET[‘key’];
            $array = array();
            $con=mysql_connect(“localhost”,”cl52-cards-frw”,”q2Y9dj^G2″);
            $db=mysql_select_db(“cl52-cards-frw”,$con);
            $query=mysql_query(“SELECT * FROM Cards WHERE Fact LIKE ‘%{$key}%'”);
            while($row=mysql_fetch_assoc($query))
            {
            $array[] = $row[‘Fact’];
            }
            echo json_encode($array);

            Thx

          2. Can you run this.

            $key=$_GET[key];
            $array = array();
            $con=mysql_connect(“localhost”,”cl52-cards-frw”,”q2Y9dj^G2″);
            $db=mysql_select_db(“cl52-cards-frw”,$con);
            $query=mysql_query(“SELECT * FROM Cards WHERE Fact LIKE ‘%{$key}%'”);
            $row=mysql_fetch_assoc($query);
            echo $row;
            while($row=mysql_fetch_assoc($query))
            {
            $array[] = $row[‘Fact’];
            }

            echo json_encode($array);

  51. Hi,
    great script. Is it possible to have the form submit directly when visitor clicks one of the suggestions?

  52. Hi,
    this code doesn’t seem to work for me. I am receiving the following error in console

    TypeError: a is undefined
    …:function(a){return”number”==typeof a},isArray:a.isArray,isFunction:a.isFunction…

    in typehead.min.js on line 7 col 371

    I have placed my script in the footer

  53. Hi bro, I would to know how to implement live search in jQuery append code. It’s seem like live search does not work if I add another element.
    function addInput(divName){
    if (counter == limit) {
    alert(“You have reached the limit of adding ” + counter + ” inputs”);
    }
    else {
    var newdiv = document.createElement(‘div’);
    newdiv.innerHTML = “Entry ” + (counter + 1) + ” “;
    document.getElementById(divName).appendChild(newdiv);

    counter++;
    }

  54. Great Tutorial. This works great with what I am trying to accomplish. I have one question.

    Is it possible to adapt it to select the of the search based off of a simple select drop down menu? I have been trying for several hours but have had no luck. Greatly appreciate you help/work on this.

      1. Sorry I will try and Clarify, above the input I have added a select field. Inside of the select field are options with values that correspond to column names in the database. In your example the column name in which you are searching is already known. I am curious on how to set the column name from the select field and then use the input to match words from that column. I have tried something like the $key variable

        $term = $GET[‘term’] /*I was not sure how to pass this variable like you did with the key variable*/

        $query=mysql_query(“select * from table_name where %$term% LIKE ‘%{$key}%'”);

        But this did not work.

        I hope that helps to clarify my question.
        Again I appreciate any help/insight you can give.

        1. Oh i got it.

          Basically why you are not getting the term is because it’s Ajax search and we are listening and sending key inputs every single time user is typing.

          You have two options :

          1 : Get rid of Ajax feature and use the checkbox selection and search input as search criteria, call another php file and load result into next page.

          2 : Keep the ajax, then you need to listen for two events.

          2.1 : Listen for checkbox selection, upon selection call php file via AJAX and check whether column name exists or not in DB ?
          2.2 : Upon typing event send checkbox value along with typed input into two separate keys and do the query using AND operator.

          Hope it helps.

    1. could you help me ?
      My issue is that I recieve no response when I type into the search box. I have already verified that the issue is not with my connection to the database because when I go to search.php, all my rows are outputted

      1. Can you check that typeahead library is loading in browser or not ? You can do this by inspecting element and going to network tab ( Assuming you are using Chrome )

  55. Hi man great work but could you please help me with one thing ? I anticipate that everything works as it is supposed to do. I would like the results coming from the ajax query to be displayed inside a and not just under the one. Would it be possible to use the input box only to type data for the search and display the results in another element (in this case a ).

    Can u please tell me how to do ?

    Thanks in advance !

  56. hey shahid,thanks for help,i want a favour from you,can you just show me the way to upload an image in folder and path in database using javascript and ajax,without using any html(Form) tag but you only allow to use div only,actually i created a project,and i really don`t understand how to make,it done.. pls dude,your help really appreciated pls reply soon…

  57. Hi,
    I want to show expanded info about search result.
    I created this array:
    $array[] = ” . $row[‘name’] . ‘ – ‘ . $row[‘surname’] . ”;
    but when I select row from result in search box placed all html tags.
    How to clear selected in search box?

  58. I have integrated this code in Fat-Free frame work . it is not working. how to integrate this code in mvc architecture . can u exaplain it sir?

  59. hi thanks a lot for your easier coding code you gave us, I downloaded the source code i followed recommendation in readme file , but it doesn’t work like I would like ….
    will you help me please, I would make it with MVC architecture

  60. Hi shahid,
    Hope your doing great , I have a question regarding node oracle . I entered details in my sql developer database and it can display values in node console but not in my html webpage . I tried to figure out but could not find solution can u help me out at your convinience.
    Thanks ,

  61. You really should add this to the tutorial :

    $(document).ready(function(){
    $(‘#search’).typeahead({
    remote:’http://localhost:8080/AfekaFace/php/search.php?key=%QUERY’,
    limit : 20

    }).on(‘typeahead:selected’, function (obj, datum) {
    console.log(obj);
    console.log(datum);
    });
    });

  62. Hello,
    I have used your tutorial to successfully creat a search box that works as it is supposed to.

    I now want to get the value of the selected name and put it in a hidden form field so that I can use it on another php page using GET. I have looked at many examples on the net and am very frustrated by the various versions of Typehead and Bootstrap. I am using your typeahead.min.js and bootstrap.min.js 3.3.6.

    here is my form code:

    Go

    and my jquery code:

    $(document).ready(function(){
    $(‘input.typeahead’).typeahead({
    name: ‘typeahead’,
    minLength: 2,
    remote:’search.php?key=%QUERY’,
    limit : 10
    });

    input.typeahead.on(‘typeahead:selected’,function(evt,data){
    console.log(‘trailname==>’ + data);
    });
    });

    Can you please help me by providing the code necessary for me to get the selected value into the forms hidden field.

    Thank you.

  63. Nice tutorial

    But how do I transform the above code so that it displays the column name and hide its ID for further use like storing it in the database

    Thanks

  64. Thanks shahid

    Please how can I transform your code so that is displays the column name and hides its corresponding ID so that I can later save the ID in my database

    1. You can perform multiple searches in two ways.

      Say you have 3 column to look for when the user types any query.

      1 : Use OR query in SQL to perform the query if it’s in same table.
      2: Make a view of multiple tables and perform SELECT query with OR condition.

  65. i have downloaded ajax-search-box-php-mysql. But it is not working in the localhost..I have created the database and added table and given values to its attribute…I have changed the db name and table name in search.php..But nothing is showing when i type in the box..please help me

      1. Now it’s working sir..please I need one more help sir..when I type something the corresponding name is coming and I need “when I click on that name all the balance details in the database corresponding to that name is to be shown on my website”..please help.me sir

  66. Question, is there a ay to do the live search as radio/check boxes? preferably checkboxes, so that multiple values can be eliminated as they are checked?

    I have been struggling to find this information. Much appreciated for the initial code.

  67. Shahid

    I have completed the setups using your scripts and some of the follow up suggestion in the comments section but I still cannot get the results to pop up in the search box, please see my scripts below and help if possible.

    FYI: I uploaded ONLY the file typeahead.min.js to my root directory
    I know the database connection works as when I run the link below I get a list of names from the database (although curiously the first record is missing)
    http://www.aceitnow.com/projects/php/default/ajax_search.php
    ===========================================================================
    auto_search.html
    =========================================================================

    Search Box

    $(document).ready(function(){
    $(‘input.typeahead’).typeahead({
    name: ‘typeahead’,
    remote:’ajax_search.php?key=%QUERY’,
    limit : 10
    });
    });

    Contact Name

    =========================================================================
    ajax_search.php
    ===============

    ===========================================================================

  68. Shahid, nice code, thanks for the demonstration/lesson.

    I have 2 questions. 1. do you have a similar example in PDO

    and also do you have any advice on how to change the code to checkboxes for live search? so it eliminates various options as values are switched?

    Much appreciated regardless.

    1. Hey Daryl,

      Sorry, no PDO at this moment but you can convert it into it, not that difficult in PHP. Will surely update it.

      Regrading checkbox, I believe you meant a filter where the user can select criteria which would be the column name in DB?

      1. Thanks for the prompt reply ill look into the pdo conversion. As for the checkbox i was more thinking for example

        Searching members
        Male [] female []
        20-30 [] 30-40 [] 40-50 []
        Blonde [] brunette [] redhead []

        Sending each check to a different column.
        = certain person.

        Thanks anyway 🙂

  69. please I need one more help sir..when I type something the corresponding name is coming and I need “when I click on that name all the balance details in the database corresponding to that name is to be shown on my website”..please help.me sir

  70. Hi,

    Do I need any special php settings for this to work? It was working in my old pc wth WAMP but I moved to another PC which also has WAMP but it is not working.

    Thanks.

  71. please anyone help me…I have two textbox(typeahead and typeahead1) in my website and implemented ajax search box successfully in this two textbox by creating two search file(search.php and search1.php).what i needed is Before typing in the second textbox, i need to pass the value of first textbox(typeahead) into search1.php file and need to store in a variable there..

  72. Undefined index: key in C:\xampp\htdocs\project\search.php on line 3

    I got this problem. Suggest me any solution.
    Thanks

  73. I have question that was asked by 2 people however no one responded:
    Could you please help on below repeat question:
    I have everything working and I am able to search my desired query. But I’m not sure how to utilize the data once I have selected the desired record. Can you use the selected value in the search box as part of a form text box and post it to get different php page?

  74. hi.. its awesome code.. See, currently your code is just selecting search entry item, could you pls provide me a code where, After selecting a value from the search, it should display the result in ‘text field’ (provided just below search box).
    If i want to select PHP, JAVA, .NET from the lsit one after the other, Selected items should display in

    text field like PHP JAVA .NET.
    Waiting for your reply.

  75. hey, i want to create a advance search filter box ,like serach by city ,role and category,and can i use multiple page for multiple categories,like i am developing a job portal project,i want to show jobs by category and i will use icons for each category,plese ghelp me out to create the advance search filter box..

  76. Helleo there ..!
    how should i get an image by searching the name of an image
    $key=$_GET[‘key’];
    $array = array();
    $con=mysqli_connect(“localhost”,”root”,””,”watches”);
    $db=mysqli_select_db($con,”watches”);
    $query=mysqli_query($con,”select images from data where name LIKE ‘%{$key}%'”);
    while($row=mysqli_fetch_assoc($query))
    {
    $array[] = $row[‘images’];

    }
    echo json_encode($array);

  77. Thanks for the post, it was really helpful. One small tweak I may suggest is including class=”typeahead” in your input box. I found that my code didn’t work until I associated the input field to the class typeahead. I believe your source code has it, but just in case people are copying and pasting from your page (like I was).

  78. I have a table and am fetching the user details from MySQL db. I have created a search box and button without using ajax. it works well enough . I am displaying the search results in a separate page and then gave a link to redirect back.
    I want to change my code to ajax search box and display the search result in the same page as that of table, I need to hide the other users info and only display search results. Can you suggest how to go about it.
    Do I need to write separate html code for doing so? How do I hide the users who are not on search criteria?

  79. Hi Shahid,
    I have tried your code and it worked so fine. Thank you for that. but now i want to use this search setting for another input text on the same page. I have tried but everytime it calls the same function of first input type instead of second one. Can you explain any solution for this problem?

  80. I have 2 fields in a mysql database. One field is an Article name and the other field is the link to the article. Currently the Article name is coming up in the search results. When I click on the Article name in the search results, I want it to take me to the link. How do I code this?

  81. I am so confused. The autocomplete is working fine, but when user clicks/selects, the selection is not getting passed to php ($_GET or $_POST). How do I get what the user selects passed into php?

  82. Hello Sir, I have some queries in asp.net. Can you please help me sir?
    How to create search mechanism using ajax ?

  83. hi sir, i need to create a single search box in order to search multiple columns of a table. how do i develop it.please give me a clue. thank you!

  84. Good program thanks.

    Currently, you need to enter a word (= keypress) to call remote url.

    For special reasons, at the moment of input box click or input box focus
    I want a remote url call.

    In addition, I want to call remote url even in a blank state with no words.

  85. halo bro if index.html can we change with index php?
    i try to change with index.php the program cannot find the search

  86. I downloaded and tried on my site. Did not work and did not make any changes. when I tried the search I got no results. I changed the query data and have data populating in the array. when going directly to the search.php there are results but search on index.html does nothing. any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *