Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Debugging AJAX Applications

Dealing with remote scripting means working with several languages at onceJavaScript, server-side languages such as PHP, XML, and of course HTML. Thus, when you find an error, it can be difficult to track down. Here are some tips for debugging AJAX applications:

  • Be sure all filenames are correct, and that all files for your application are in the same folder on the server.

  • If you are using a server-side language, test it without the script: Load it in the browser and make sure it works, and try passing variables to it in the URL and checking the results.

  • Check the statusText property for the results of your requestan alert message is helpful here. It is often a clear message such as "File not found" that might explain the problem.

  • If you're using a third-party AJAX library, check its documentationmany libraries have built-in debugging features you can enable to examine what's going on.

Did you Know?

Hour 16, "Debugging JavaScript Applications," includes more information on JavaScript debugging in general and includes descriptions of some useful debugging tools.


Try It Yourself

Making a Live Search Form

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 Form

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.

The PHP Back End

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:

  • Sams Teach Yourself PHP in 10 Minutes; ISBN: 0672327627

  • Sams Teach Yourself PHP in 24 Hours; ISBN: 0672326191


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.

The JavaScript Front End

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.

Making It All Work

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.

Figure 17.2. The live search example as displayed by Firefox.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Hour 15. Unobtrusive Scripting
Hour 16. Debugging JavaScript Applications
Hour 17. AJAX: Remote Scripting
Introducing AJAX
Using XMLHttpRequest
Creating a Simple AJAX Library
Creating an AJAX Quiz Using the Library
Debugging AJAX Applications
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 18. Greasemonkey: Enhancing the Web with JavaScript
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele