AJAX - The Complete Reference

(avery) #1

386 Part II: Developing an Ajax Library^


NNOT EOTE The appid value has been removed from the code listing and replaced with a string of “X”
characters. If you want to perform this example yourself, you should apply for an appropriate
appid with Yahoo. However, you are free to run it online at the book support site without
applying for one.

When the result is returned from the service, the server-side PHP program pipes the
result back, and the XHR object will then invoke the handleResponse() function that is
set as a callback. Given that the result is in JSON format, we have fairly easy access to its
contents. However, as we can see in the following code, it is still necessary to loop over the
returned items and add them into the page.

function handleResponse(response)
{

var query = response.query;
var results = AjaxTCR.data.decodeJSON(response.xhr.responseText);
var items = results["ResultSet"]["Result"];
if (items.length > 0)
{
var resultsDiv = document.getElementById("results");
resultsDiv.innerHTML = "";
for (var i=0;i<items.length;i++)
{
var item = items[i];
var size = "";
if (item["Cache"] && item["Cache"]["Size"])
size = " - " + item["Cache"]["Size"];
resultsDiv.innerHTML += "<a href=\"" + item["Url"] + "\">" +
item["Title"] + "</a><br/>" + item["Summary"] + "<br/>";
resultsDiv.innerHTML +="<span style=\"color:green;\">" +
item["DisplayUrl"] + size + "</span><br/><br/>";
}
document.getElementById("searchTerm").innerHTML = " for " + query;
}
document.getElementById("loadingMsg").innerHTML = "";
document.getElementById("resultsContainer").style.display = "block";
gRunning = false;
}
}

The complete example can be found at http://ajaxref.com/ch8/autosearch.html and is
demonstrated in Figure 8-12.

Auto Validation


Probably the oldest application of JavaScript is form validation. With the rise of Ajax, there
are certainly ways to improve form validation, as well as ways to do it just as badly as
before. Consider a very simple U.S. ZIP code validation. You might check to make sure that
the ZIP code was in an appropriate format of either five digits or five digits plus four digits
before allowing it.
Free download pdf