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:-
<html>
<head>
<script type="text/javascript" src="search.js"></script>
<title>
AJAX Search Example
</title>
</head>
<body>

<form>
Name: <input type="text" name="name" onkeyup="search(this.value);" />
</form>
<p>Search Results: <span id="txtResult"></span></p>

</body>
</html>

As you can see we have included a JavaScript source file search.js in the header section of our HTML code. All corresponding JavaScript code will be stored in search.js. The content of search.js is shown below - 

function search(username)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
else
  {
  alert("Sorry, your browser seems to not support XMLHTTP functionality.");
  }


xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
  {
  document.getElementById("txtResult").innerHTML=xmlhttp.responseText;
  }
}
var url="ajax_search.php";
url=url+"?q="+username;
url=url+"&sid="+Math.random();
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
/*It has been assumed here that ajax_search.php is in the same directory.*/
xmlhttp.send(null);
}

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:-

<?php
$users=(file("usernames.txt"));

//get the q parameter from URL
$query=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($query) > 0)
  {
  $result="";
  for($i=0; $i<count($users); $i++)
    {
    if (strtolower($query)==strtolower(substr($users[$i],0,strlen($query))))
      {
      if ($result=="")
        {
        $result=$users[$i];
        }
      else
        {
        $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";
  }
else
  {
  $response=$result;
  }

//output the response
echo $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.
 

Name:

 

Search Results:

 

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.

Comments

Member since:
21 February 2009
Last activity:
4 years 32 weeks

Hi scripter,

You can modify the code of ajax_search.php to acheive this. All you have to do is that establish a MySQL connection, query your MySQL table for the username and if it matches then display an error message thorugh AJAX. A tutorial on this will be published soon.

Member since:
17 March 2010
Last activity:
4 years 32 weeks

Do you have a similar tutorial for the AJAX Username Checker where the usernames are stored in a MySQL dayabase table?