Web Programming Step by Step
Web Programming Step by Step
Lecture 19
Ajax
Reading: 10.1 - 10.2
Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp
and Jessica Miller.
asynchronous: user can keep interacting with page while data loads
communication pattern made possible by Ajax
XMLHttpRequest (and why we won't use it)
JavaScript includes an XMLHttpRequest object that can fetch files from a web server
supported in IE5+, Safari, Firefox, Opera, Chrome, etc. (with minor compatibilities)
it can do this asynchronously (in the background, transparent to user)
the contents of the fetched file can be put into current web page using the DOM
sounds great!...
... but it is clunky to use, and has various browser incompatibilities
Prototype provides a better wrapper for Ajax, so we will use that instead
construct a Prototype Ajax.Request object to request a page from a server using Ajax
constructor accepts 2 parameters:
1. the URL to fetch, as a String,
2. a set of options, as an array of key : value pairs in {} braces (an anonymous JS
object)
hides icky details from the raw XMLHttpRequest; works well in all browsers
event description
onSuccess request completed successfully
onFailure request was unsuccessful
onException request has a syntax error, security error, etc.
onCreate, onComplete, on### (for HTTP error code ###)
events in the Ajax.Request object that you can handle
Basic Prototype Ajax template
new Ajax.Request("url",
{
method: "get",
onSuccess: functionName
}
);
...
function functionName(ajax) {
do something with ajax.responseText;
}
function handleRequest(ajax) {
alert(ajax.responseText);
}
for user's (and developer's) benefit, show an error message if a request fails
Debugging Ajax code
Net tab shows each request, its parameters, response, any errors
expand a request with + and look at Response tab to see Ajax result
Ajax.Updater fetches a file and injects its content into an element as innerHTML
additional (1st) parameter specifies the id of element to inject into