|
One of the most impressive demonstrations of AJAX is live search: Whereas a normal search form requires that you click a button and wait for a page to load to see the results, a live search displays results within the page immediately as you type in the search field. As you type letters or press the backspace key, the results are updated instantly to make it easy to find the result you need.
Using the AJAX library you created earlier, live search is not too hard to implement. This example will use a PHP program on the server to provide the search results, and can be easily adapted to any search application.
Watch Out!
Once again, because it uses AJAX, this example requires a web server. You'll also need PHP version 3 or later, which is available on most servers.
The HTML for this example simply defines a search field and leaves some room for the dynamic results. The HTML document is shown in Listing 17.5.
Listing 17.5. The HTML File for the Live Search Example
<html>
<head>
<title>Live Search Ajax Example</title>
<script language="javascript" type="text/javascript"
src="ajax.js">
</script>
</head>
<body>
<h1>Live Search: Ajax Example</h1>
<form>
<p>
<b>Search for:</b> <input type="text" size="40" id="searchlive">
</p>
<div id="results">
<ul id="list">
<li>Results will display here.</li>
</ul>
</div>
</form>
<script language="javascript" type="text/javascript"
src="search.js">
</script>
</body>
</html>
|
This HTML document includes the following:
The <script> tag in the <head> section includes the AJAX library, ajax.js. The <script> tag in the <body> section includes the search.js script, which you'll create next. The <input> element with the id value searchlive is where you'll type your search query. The <div> element with the id value results will act as a container for the dynamically fetched results. A bulleted list is created with a <ul> tag; this will be replaced with a list of results when you start typing.
Next, you'll need a server-side program to produce the search results. This PHP program includes a list of names stored in an array. It will respond to a JavaScript query with the names that match what the user has typed so far. The names will be returned in XML format. For example, here is the output of the PHP program when searching for "smith":
<names>
<name>John Smith</name>
<name>Jane Smith</name>
</names>
Although the list of names is stored within the PHP program here for simplicity, in a real application it would more likely be stored in a databaseand this script could easily be adapted to work with a database containing thousands of names. The PHP program is shown in Listing 17.6.
Listing 17.6. The PHP Code for the Live Search Example
<?php
header("Content-type: text/xml");
$names = array (
"John Smith", "John Jones", "Jane Smith", "Jane Tillman",
"Abraham Lincoln", "Sally Johnson", "Kilgore Trout",
"Bob Atkinson","Joe Cool", "Dorothy Barnes",
"Elizabeth Carlson", "Frank Dixon", "Gertrude East",
"Harvey Frank", "Inigo Montoya", "Jeff Austin",
"Lynn Arlington", "Michael Washington", "Nancy West" );
if (!$query) $query=$_GET['query'];
echo "<?xml version=\"1.0\" ?>\n";
echo "<names>\n";
while (list($k,$v)=each($names)) {
if (stristr($v,$query))
echo "<name>$v</name>\n";
}
echo "</names>\n";
?>
|
This hour is too small to teach you PHP, but here's a summary of how this program works:
The header statement sends a header indicating that the output is in XML format. This is required for XMLHttpRequest to correctly use the responseXML property. The $names array stores the list of names. You can use a much longer list of names without changing the rest of the code. The program looks for a GET variable called query and uses a loop to output all of the names that match the query. Because PHP can be embedded in an HTML file, the <?php and ?> tags indicate that the code between them should be interpreted as PHP.
Did you Know?
The following books are good resources if you want to learn more on PHP quickly:
Save the PHP program as search.php in the same folder as the HTML file. You can test it by typing a query such as search.php?query=John in the browser's URL field. Use the View Source command to view the XML result.
Finally, the JavaScript for this example is shown in Listing 17.7.
Listing 17.7. The JavaScript File for the Live Search Example
// global variable to manage the timeout
var t;
// Start a timeout with each keypress
function StartSearch() {
if (t) window.clearTimeout(t);
t = window.setTimeout("LiveSearch()",200);
}
// Perform the search
function LiveSearch() {
// assemble the PHP filename
query = document.getElementById("searchlive").value;
filename = "search.php?query=" + query;
// DisplayResults will handle the Ajax response
ajaxCallback = DisplayResults;
// Send the Ajax request
ajaxRequest(filename);
}
// Display search results
function DisplayResults() {
// remove old list
ul = document.getElementById("list");
div = document.getElementById("results");
div.removeChild(ul);
// make a new list
ul = document.createElement("UL");
ul.id="list";
names = ajaxreq.responseXML.getElementsByTagName("name");
for (i = 0; i < names.length; i++) {
li = document.createElement("LI");
name = names[i].firstChild.nodeValue;
text = document.createTextNode(name);
li.appendChild(text);
ul.appendChild(li);
}
if (names.length==0) {
li = document.createElement("LI");
li.appendChild(document.createTextNode("No results"));
ul.appendChild(li);
}
// display the new list
div.appendChild(ul);
}
// set up event handler
obj=document.getElementById("searchlive");
obj.onkeydown = StartSearch;
|
This script includes the following components:
A global variable, t, is defined. This will store a pointer to the timeout used later in the script. The StartSearch() function is called when the user presses a key. This function uses setTimeout() to call the LiveSearch() function after a 200-millisecond delay. The delay is necessary so that the key the user types has time to appear in the search field. The LiveSearch() function assembles a filename that combines search.php with the query in the search field, and launches an AJAX request using the library's ajaxRequest() function. The DisplayResults() function is called when the AJAX request is complete. It deletes the bulleted list from the <div id="results"> section, and then assembles a new list using the W3C DOM and the AJAX results. If there were no results, it displays a "No results" message in the list. The final lines of the script set the StartSearch() function up as an event handler for the onkeydown event of the search field.
To try this example, you'll need three files on a web server: ajax.js (the library), search.js (the search script), and the HTML file. Figure 17.2 shows this example in action.
|