AJAX Search Tutorial
This tutorial is in continuation with our previous tutorial on AJAX - AJAX Basic Tutorial. But even if you have basic knowledge of AJAX then you can read this tutorial directly. Here we will be developing a search feature. By using this feature the users will be able to search for a particular person in a list stored on the web server in text format.
Let’s start by declaring a textbox inside a HTML form and a span element as shown below:-
AJAX Search Example
Name: <input type="text" name="name" onkeyup="search(this.value);" />
<p>Search Results: <span id="txtResult"></span></p>
// code for IE7+, Firefox, Chrome, Opera, Safari
else if (window.ActiveXObject)
// code for IE6, IE5
alert("Sorry, your browser seems to not support XMLHTTP functionality.");
/*It has been assumed here that ajax_search.php is in the same directory.*/
Here first of all we check whether the user has XMLHttp functionality or not. This also has been explained in the previous tutorial in detail. Next we load the data from the server in the txtResult which is a span element. After this we have declared a variable url which contains the path to our php file (ajax_search.php – this will be containing server side script) along with it the data which user enters in the textbox name is added as q parameter and Math.random() is further added to url to avoid page caching.
Now the code for ajax_search.php is:-
//get the q parameter from URL
//lookup all hints from array if length of q>0
if (strlen($query) > 0)
for($i=0; $i<count($users); $i++)
$result=$result." , ".$users[$i];
// Set output to "No Search Results Found" if no results were found
// or to the correct values
if ($result == "")
$response="No Search Results Found";
//output the response
This code is pretty much self explanatory. Firstly the contents of usernames.txt file are loaded in an array $users. usernames.txt should have one name per line. Next we compare these names stored in the array $users with the $query. $query contains the q parameter i.e. the value of the textbox name entered by the user. If the value of $query matches with any part of the various values present in $user array then this value is stored in a variable ‘$response’ which is then sent back.
Output of the above example
Try typing an alphabet in the name textbox and it will show the search results below it.
This example must have given you an idea as to how you can use AJAX with server side scripts to provide advanced functionality to users. In next tutorial we will be discussing how we can AJAX to extract data from SQL database and display it.
If you have any query regarding this tutorial post it right away. Feedbacks and suggestions are welcome.