Simple PHP & Ajax search tutorial.

This is a short guide on how to build a simple search form using PHP and Ajax. In this tutorial, we will use the JQuery library to carry out an Ajax request to a PHP file, which will return our search results. This example can be adapted to search database tables, etc.

Let’s take a look at the HTML page that will contain our search form and JavaScript. I have added comments to the code so that you can better understand what is going on:

A quick summary:

  • We created a simple text input field and a search button.
  • We also created an empty div called “search_results”. We will populate this div with our search results once the Ajax request to our search.php file has been successfully completed.
  • We added a JQuery onclick event listener to our search button.
  • When the user clicks on the search button, we blank the “search_results” div and send a simple Ajax request to our search.php file. In our request, we include the search term that the user entered as a GET parameter in the Ajax request. In the example above, we call this parameter “q”, which is short for “query”.
  • When our PHP file returns the search results, we loop through the array and append it to our “search_results” div.

The code for the PHP file is pretty straight forward:

In the example code above, we basically search an array of city names and return the results in a JSON format. If we wanted to, we could easily modify the PHP code above to search a particular MySQL table instead of an array. See: Ajax search with MySQL, PHP and JQuery.

Hopefully, this tutorial set you down the right path!