Ajax Live Search – PHP Tutorial

In this tutorial we’re using jQuery and PHP to build a Ajax live search feature for your website. A live search doesn’t need to reload the whole page and show the search results based on the currently entered keyword. For your website visitor is this a much better experience. Be careful with this kind of features if your database is very big: A new database query is done every time when the visitor enters the next character! Click here and try our demo which makes it possible to search this website.

jQuery / PHP / MySQL tutorial

We start our jQuery Ajax Live Search tutorial with the PHP code part. Create a new PHP script and name it “search.php”. In this script we need to connect to our MySQL database and based on the posted string we will do a database query. In case of a positive match, the script will loop through the result set and will add the values to an associative array. At the end the script will return this array formatted as a JSON string. If you like you can try the example code from the tutorial for a live search on the database from this WordPress website.

PHP script with database access

The first four rows are the database settings we need to connect to the database. Replace the default values with your own settings. We use the “newer” MySQLi extension which performs better and works in an OOP context. If the connection fails the script returns the MySQL error number and string.

Here we create an empty array first and if the $_POST[‘keywords’] variable isn’t empty the database query is executed. Next, the script will loop through the result set and will add the values to the array $arr. At the end the script will “echo” the JSON formatted string. That was so far the only PHP code we need, let’s continue to the HTML file.

I created a new file and named it “index.html”. Next, I added some standard HTML template code and included also the jQuery library. For this tutorial I used the CDN version provided by Google, which loads very fast and is very popular. Many Internet users have a copy in their web browser’s cache memory. All JavaScript code is placed right before the closing BODY tag for the best performance. We have a simple form with only a single form field. A form button is not necessary because we will submit the form by a jQuery event. Add the following code below the tag where the jQuery library is included.

The following code is used as trigger and will “collect” the search values from the form element.

The following code will post the search value to the search.php file, but only if the search value is equal or longer than 3 characters.

The function post is very similar to how a HTML form works, but it gives us the possibility to collect some callback in response. If the file search.php returns any data we remove first anything from the UL element with the ID “content”. The “each” loop is used to create new list elements for each of the returned data pairs (ID and post title).

The complete HTML page with form and jQuery code

You can see it’s very easy to use jQuery for some nice user interface. The jQuery part is actually one a view rows of code. For debugging some jQuery code, you should install the firebug extension for your web browser. Both, the demo and the example code are enhanced with the Bootstrap CSS framework. We removed this extra code from the tutorial to keep it simple. Our live search demo is a bit different from the tutorial, because we’re using a different database. You can download the source code here.

12 Responses

  1. Hi, i have 1 question:

    i have 2 tables, 1 for my clients and other for my products. I want make this search for 2 tables in same time. I tried use UNION in my code, but i need to know how table the rows came. If u can help me i appreciate. :)

    1. Hi,
      what is your current query? Do you checked the MySQL manual for LEFT, RIGHT and INNER JOIN statements?
      From the nature of a client and product data, it might be not really useful to have a single search box for a mix of both data sets.
      It will help if your write down the result set first, based on this you can see which data keys might be used for the JOIN statement.

  2. Hi. This code is great, I am using for live search results. However, I have noticed one odd behavior: I get different/duplicate/incomplete search results if I type quickly in the search box. If I delete the last few characters of my search, and re-type them more slowly, I get the expected results.

    I don’t think the query results are changing, as the query always returns the same number of records when I run it against the database.

    Is there a delay or some kind of refresh I can introduce to prevent this from happening?

    1. Hello Chris,

      right, that sounds strange. Maybe the PHP file (or your webhost) isn’t fast enough to return the data on time? Do you have the same problem with my own demo?

  3. Thanks Olaf. The problem definitely does not exist on your demo. Yours responds instantly, unlike mine, which has a slight lag (which isn’t unpleasant). I’ll keep digging on my end.

  4. I found the problem, it had nothing to do with your code. I had a function that highlights the terms in the search results that didn’t work properly. All good now.

  5. So, first, forgive me as I’m a MySQL/PHP novice, to put it kindly. I’ve inserted the code you’ve provided, using an input form-group, and can view the POST action in the console, but don’t get any results listed in any case. I think this may be because I have one empty database, and thus matches aren’t being made. My question is: Do my pages need to be indexed or otherwise registered in the database specified in my NAME connection string? What am I missing?

    Thanks very much for your tutorial, it looks very versatile!


    1. Adrian,
      You don’t need to index your site, because this example is used together with a query on a single database table. Sure you can extend the PHP script according your own requirements, but this isn’t part of the tutorial

  6. Great script! Is there a way to clear the list of results if I remove the data in the textbox? Kind of like starting over.

    1. Hi John,

      thanks for your comment. I know about both functions, but append() is the right function for this example. The function is used in a loop and if you would use html() instead, the list of results would be always just one result.

Leave a Reply

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

Don’t post your code here!
Post your code block or snippet to pastebin and include the pastebin URL in your comment.

I delete all comments with non related links inside the comment text. Keep your comment related to the topic, if your question is off-topic, please use the contact form instead.