Create Ajax Based Searching System with PHP and jQuery

Google Suggest is a perfect example of Ajax based searching. Whenever you enter any letter in the search box Google suggest starts showing you some “suggestions”. How those suggested elements come to you? It’s because of Ajax. Whenever you enter any letter in Google search box a javascript runs behind the scene and passes that letter to some other script which interacts with database and comes up with relevant suggestion results.

In this tutorial you will learn how to develop your own Ajax based search system. I have created a live demo of this tutorial for you. In Live demo database has some records with the name of cricketers and some dummy data.

Click here to see LIVE DEMO- Ajax Based search system.

Let’s start the simple tutorial to develop your own Ajax based search system. In this tutorial we have created a table in our database(“userdata”). Table name is “userdetail” it has three columns “id”, “name” and “email”. Here is the SQL query to create userdetail table in your database:

CREATE TABLE IF NOT EXISTS <code>userdetail</code> (
<code>id</code> int(10) NOT NULL AUTO_INCREMENT,
<code>Name</code> varchar(20) NOT NULL,
<code>Email</code> varchar(50) NOT NULL,
PRIMARY KEY (<code>id</code>)
);

 Now you have to create an html form that will take search-input from user. Using jQuery get the form data as soon as user enters the first letter. Using jQuery’s ajax method send this data to another php script which will search database for the “serach query”. And the result will be displayed without any delay just below the search field.

I have created “index.html” which has code for creating form and jQuery code. And “search.php” to search database and fetch relevant results.

Code for INDEX.PHP:

<html>
<head>
<title>Ajax Based Search- InfoTuts</title>
<style type="text/css" >
#main {
padding: 10px;
margin: 100px;
margin-left: 300px;
color: Green;
border: 1px dotted;
width: 520px;
}
#display_results {
color: red;
background: #CCCCFF;
}
</style>
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#button_find").click(function(event){
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way();
});

});

function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this}, function(data){
$("#display_results").html(data);

})
}
</script>
</head>

<body>
<div id="main">
<h1>Ajax Based Search System- InfoTuts</h1>
<form id="searchform" method="post">

<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="submit" value="Search" id="button_find" />

</form>
<div id="display_results"></div>
</div>
</body>
</html> 

Here is code for “search.php”:

<?php
$connection = mysql_connect('localhost', 'root', '12345');
$db = mysql_select_db('userdata', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term); // Attack Prevention
if($term=="")
echo "Enter Something to search";
else{
$query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
$string = '';

if (mysql_num_rows($query)){
while($row = mysql_fetch_assoc($query)){
$string .= "<b>".$row['name']."</b> - ";
$string .= $row['email']."</a>";
$string .= "<br/>\n";
}

}else{
$string = "No matches found!";
}

echo $string;
}
?>

 I hope you liked this tutorial. This tutorial is implementation of an article from IBM developer works, you can check it here. You can easily integrate this script in your web-projects. Comment below if you have any problems or if you want a copy of this script directly in your Inbox.

About sanjeev

sanjeev
Dreamer, Blogger and Thinker. I love to help people in solving their problems. You can also join me HERE

Related posts:

50 Responses so far.

  1. Hi,

    I am trying to implement your search method but once I enter anything in my search box, nothing happens next.

    I am new to ajax. Can you help me understand the purpose of find23php and your actual php is named as search.php.
    How do you call search.php ?

    Thanks much.

  2. Hi Alice,

    Yeah that’s search.php. replace find23.php with search.php and your code would work. Will inbox you well commented code, you can easily get whats going on with each line of code.

    Sanjeev

    1. hi i like to know,how to combine both of your crud and search process together,so user get result faster,please reply soon

  3. Thanks again for your reply.
    I tried your script as it is, yesterday. And it was working fine until this morning, so I switched again with your updated script and works fine. What did you change?

  4. Hello Sanjeev!
    I tried your code and it seems to be working for me. :)
    I would have two questions.

    1. Why did you put connection in the query at line 9?

    2. Would it be hard to add to this code that make a search with the result? Like in Google Search: I am starting typing the word, I get the result and then I wanna click on that to make a new search which of course would go on a new page?

  5. I think I was confusing, sorry for that.

    http://www.tv.com/

    Please check the search field there, is it easy to do the same? I understood you have solved that with search.php. Since I know only PHP I am not sure how did they make to hover the search result over the original webpage, with javascript,ajax?

    1. Hi Zoltan,

      Yes that can also be implemented with some more code and logics. It should not be that much difficult 😉

  6. The above code is working on my system but at the time of selection if 3 items found it selects all 3 instead of single one. .
    my code is:
    search.php:-

    Ajax Based Search- InfoTuts

    #main {
    padding: 10px;
    margin: 100px;
    margin-left: 300px;
    color: Green;
    border: 1px dotted;
    width: 520px;
    }
    #display_results {
    color: red;
    background: #CCCCFF;
    }

    $(document).ready(function(){
    $(“#search_results”).slideUp();
    $(“#button_find”).click(function(event){
    event.preventDefault();
    search_ajax_way();
    });
    $(“#search_query”).keyup(function(event){
    event.preventDefault();
    search_ajax_way();
    });

    });

    function search_ajax_way(){
    $(“#search_results”).show();
    var search_this=$(“#search_query”).val();
    $.post(“search1.php”, {searchit : search_this}, function(data){
    $(“#display_results”).html(data);

    })
    }

    Enter

    search1.php:-
    <?php
    mysql_connect("localhost", "root","");
    mysql_select_db("onlineshop");

    $term = strip_tags(substr($_POST['searchit'],0, 100));
    $term = mysql_real_escape_string($term); // Attack Prevention
    if($term=="")
    echo "Enter Something to search";
    else{
    $query = mysql_query("select prod_name,prod_id from product where prod_name like '{$term}%'");
    $string = '';
    $string1='';
    if (mysql_num_rows($query))
    {
    while($row = mysql_fetch_assoc($query))
    {
    $string .= "“.$row[‘prod_name’].”“;

    $string1 .= ““.$row[‘prod_id’].”“;
    $string .= “\n”;
    }

    }
    else{
    $string = “No matches found!”;
    }

    ?><a href="productdetails.php?id=''”> <?php echo $string."”;?>
    product details.php:-

    Product NamePriceDescription

  7. If you are having issues with only one result being listed see the corrected code as to why:

    
    <?php
    $connection = mysql_connect('localhost', 'root', '12345');
    $db = mysql_select_db('userdata', $connection);
    $term = strip_tags(substr($_POST['searchit'],0, 100));
    $term = mysql_escape_string($term); // Attack Prevention
    if($term==""){
    echo "Enter Something to search";
    }else{
    $query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
    $string = '';
    
    if (mysql_num_rows($query)){
    while($row = mysql_fetch_assoc($query)){
    $string .= "<b>".$row['name']."</b> - ";
    $string .= $row['email']."</a>";
    $string .= "<br/>\n";
    echo $string;
    }
    
    }else{
    $string = "No matches found!";
    echo $string;
    }
    
    
    }
    ?>
    

    The issue is the $string variable was being echoed once and outside of the while loop. It needs to be echoed inside the while loop after the $string variable was defined as well as inside of the else block in the event there was no results from the query. Thanks for posting the code.

    Also, lines 6 – 8 were missing the appropriate brackets.

  8. i don’t understand the name searchit.because i was implement the code with some modification form when i run the code say undefined index searchit!!

    1. Hi abu,

      searchit is the parameter you sent to “search.php” via ajax. While modifying your code you would have messed up with this por renamed it to something else. Check your code again.

      Thanks:
      Sanjeev

  9. Hi i am new to ajax and php i got your code it is really working good but i am able to understand the ajax code can you please replay me with the clear explanation of data flow from the above code

  10. Good samples. One question though: I implemented your code to search against a list of last names stored in a database. The behavior I am seeing is if there is only ONE unique lastname, the results will display that lastname only and only if I type the 1st letter. After the 1st letter the display record returns blank.

    Example:
    Last Names stored in the DB:
    Smith
    Smith
    Doe
    Davies
    Davies
    Johnson
    Johnson

    If I search for “Doe”, I type the letter D and it displays all last names that start with D. But once I type the 2nd letter “o” the display results blanks out.

    Any clues?

    thanks

    1. Hi Chuck,

      There should not be any issue in this case. As all the records are returned depending on your sql query. Just for clarification I changed the data of live demo as per your condition. Now it has only four values 3 times “sanjeev” and 1 “sunday”. and its is working fine. please check it here. LIVE DEMO AJAX SEARCH

      1. Hi Sanjeev,

        I see. Then I contribute this error to my display output subroutine which could be related to ajax or my css. Thanks for looking into it.

        -C

      2. I used a do-while loop instead of a while loop and that fixed my issue. do-while loops check the truth expression at the end of each iteration instead of in the beginning.

        thanks

        -C

      3. how you do like search for four different table.
        like if some one search a it will auto show suggestion from all table that start from a. and show what it belongs to.

      4. Sir,
        I have used this code,but its not working in Internet Explorer.Can please help me with this to fix it up?

  11. i wanted to use jquery on the search results that appear on typing something in the search bar.
    but it is not working. any ideas?

  12. I need to pass now a second “hidden” input variable to search.php. Does any one know the magic to make this happen in the section?

    I have added <input type="hidden" value="” name=”search_var2″ /> to the form section.

    My search.php is waiting for $term1 = $_POST[‘search_var2’];

    My guess is that I have to modify my function search_ajax_way() but not sure how to proceed.

    Any clues?

    -C

    1. ok I figured it out. Just had to add a second var under the function search_ajax_way() function and also added it to the .post portion. Works like a charm

      -C

  13. thanks for your good kind heart for this work of yours, let me ve a copy of it. Thank you.

  14. Hey,
    Thanks for this tutorial, it was really great and I got it working pretty well. I did have a couple of questions though.
    First, how would you make it so that the results were shown in more of a drop down box (kind of like how google does it).
    Secondly, how would you make it so that you could click on one of the results and it would automatically put it in the search bar for you.

    Thanks in advance.

  15. Great tutorial thank you.
    I do have a few questions though.
    First, how would you get the results to be in more of a drop down box format (like google)?
    Second, how would you make it so that if you click on a result and it would automatically put it in the search bar for you?

    Thanks.

  16. I am using your code..I can see it’s connecting to the database, but it’s not coming up with the results. I have made no changes to the index.html and search.php code.
    For example, I have the name: Susan and email: susan@hotmail.com, when I search for “Su”
    the script comes up with these results. The other functions such as not finding a name or rejecting a blank field works as intended.

    Notice: Undefined index: name in C:\xampp\htdocs\search.php on line 15

    Notice: Undefined index: email in C:\xampp\htdocs\search.php on line 16

  17. hii….dear

    your post is very nice.like it.

    but one thing ,after write some text inside textbox the data fetch from database and display ..right…but i cannot select one amoung that displayed data….please suggest…

    Thanks in Advance…

  18. Can you send me a commented code as well? I am new to web development and would love to understand the different sections of the code.

    thanks!

  19. Hello All,
    Actually , I am filling one text field and show data in other text field respect first filed data using ajax.How can it?

    Thanks in advance.

  20. It works fine. However if the data stored in the database are in traditional chinese characters, I can’t search it out by the script. I think it comes from the code on line 4,5 in search.php. Could you give some suggestion.

    Thanks.

  21. Thank you very much for the tutorial. With a few modifications, this was exactly what I was looking for. Very well explained and works right out of the box. Appreciate you sharing your work with everyone!

  22. Thank you very much for this easy tutorial. I’ve been searching for a bit now and this was by far the easiest to implement and worked right away! Thank you for sharing.

  23. Hello sir
    Truly, your all feature are to good for used and understand. Thanks lot for sharing this feature with us. Sir i have a request to you. I have need a Auto Searching System with database for my site in which both English and Hindi can be searched with auto suggest. Plz. upload a Auto suggest Searching System.

Comments are closed.