AJAX can be used for a more user-friendly and interactive search.


AJAX Live Search

In this example we will demonstrate a live search, where you get search results while you type.

Live search has many benefits compared to traditional searching:

  • Results are shown as you type
  • Results narrow as you continue typing
  • If results become too narrow, remove characters to see a broader result

Search for a W3Schools page in the input field below:

In the example above, the results are found in an XML document (links.xml). To make this example small and simple, only eight results are available.


Example Explained – The HTML page

The HTML page contains a link to an external JavaScript, some style definitions, an HTML form, and a div element:

<html>
<head>
<script type="text/javascript" src="livesearch.js"></script>
<style type="text/css">
#livesearch
{
margin:0px;
width:194px;
}
#txt1
{
margin:0px;
}
</style>
</head>
<body>

<form>
<input type="text" id="txt1" size="30" onkeyup="showResult(this.value)" />
<div id="livesearch"></div>
</form>

</body>
</html>

The HTML form works like this:

  1. An event is triggered when the user presses, and releases a key in the input field
  2. When the event is triggered, the function showResult() is executed
  3. The <div id="livesearch"> is a placeholder for the data returned from the showResult() function

Example Explained – The JavaScript code

This is the JavaScript code stored in the file "livesearch.js":

var xmlhttp;

function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
xmlhttp=GetXmlHttpObject()
if (xmlhttp==null)
{
alert ("Your browser does not support XML HTTP Request");
return;
}
var url="livesearch.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged ;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

The GetXmlHttpObject() function is the same as in the PHP AJAX Suggest chapter.

The showResult() Function

This function executes every time a character is entered in the input field. If there is no input in the text field (str.length == 0), the function sets the return field to empty and removes the border around it. However, if there is any input in the text field, the function executes the following:

  1. Calls the GetXmlHttpObject() function to create an XMLHTTP object
  2. Defines the URL (filename) to send to the server
  3. Adds a parameter (q) to the URL with the content of the input field
  4. Adds a random number to prevent the server from using a cached file
  5. Each time the readyState property changes, the stateChanged() function will be executed
  6. Opens the XMLHTTP object with the given URL
  7. Sends an HTTP request to the server

The stateChanged() Function

This function executes every time the state of the XMLHTTP object changes. When the state changes to 4 ("complete"), the content of the txtHint placeholder is filled with the response text, and a border is set around the field.


Example Explained – The PHP page

The PHP page called by the JavaScript code is called "livesearch.php".

The code searches an XML file for titles matching the search string and returns the result as HTML:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName(‘link’);

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

//lookup all links from the xml file if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName(‘title’);
$z=$x->item($i)->getElementsByTagName(‘url’);
if ($y->item(0)->nodeType==1)
{
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="<a href=’" .
$z->item(0)->childNodes->item(0)->nodeValue .
"’ target=’_blank’>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
else
{
$hint=$hint . "<br /><a href=’" .
$z->item(0)->childNodes->item(0)->nodeValue .
"’ target=’_blank’>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>

If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:

  1. PHP creates an XML DOM object of the "links.xml" file
  2. Loops through allĀ  <title> elements to find titles that match the text sent from the JavaScript
  3. Sets the correct link and title in the "$response" variable. If more than one match is found, all matches are added to the variable
  4. If no matches are found, the $response variable is set to "no suggestion"
  5. Output the $respone variable to the "livesearch" placeholder