Lecture 18
Ajax
Reading: 10.1 - 10.2
Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.
Synchronous web communication
(10.1)
- synchronous: user must wait while new pages load
-
the typical communication pattern used in web pages (click, wait, refresh)
-
web application: a dynamic web site that mimics the feel of a desktop app
-
Ajax: Asynchronous JavaScript and XML
- not a programming language; a particular way of using JavaScript
- downloads data from a server in the background
- allows dynamically updating a page without making the user wait
- avoids the "click-wait-refresh" pattern
-
examples: UW's CSE 14x Diff Tool, Practice-It;
Google Suggest
Asynchronous web communication
- asynchronous: user can keep interacting with page while data loads
-
communication pattern made possible by Ajax
- 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
A typical Ajax request
- user clicks, invoking an event handler
- handler's code creates an
XMLHttpRequest
object
XMLHttpRequest
object requests page from server
- server retrieves appropriate data, sends it back
XMLHttpRequest
fires an event when data arrives
- this is often called a callback
- you can attach a handler function to this event
- your callback event handler processes the data and displays it
Prototype's Ajax model
(10.2.4)
new Ajax.Request("url",
{
option : value,
option : value,
...
option : value
}
);
- construct a Prototype
Ajax.Request
object to request a page from a server using Ajax
- constructor accepts 2 parameters:
- the URL to fetch, as a String,
-
a set of , 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
Prototype Ajax options
option |
description |
method
|
how to fetch the request from the server (default "post" )
|
parameters
|
query parameters to pass to the server, if any (as a string or object)
|
asynchronous
|
should request be sent asynchronously in the background? (default true )
|
others: contentType , encoding ,
requestHeaders
|
new Ajax.Request("http://www.example.com/foo/bar.txt",
{
method: "get",
parameters: {name: "Ed Smith", age: 29},
...
}
);
Prototype Ajax event options
event |
description |
onSuccess
|
request completed successfully
|
onFailure
|
request was unsuccessful
|
onException
|
request has a syntax error, security error, etc.
|
others: onCreate , onComplete ,
on### (for HTTP error code ###)
|
new Ajax.Request("http://www.example.com/foo.php",
{
parameters: {password: "abcdef"},
onSuccess: mySuccessFunction
}
);
Basic Prototype Ajax template
new Ajax.Request("url",
{
method: "get",
onSuccess: functionName
}
);
...
function functionName(ajax) {
do something with ajax.responseText;
}
- attach a handler to the request's
onSuccess
event
- the handler takes an Ajax response object, which we'll name
ajax
, as a parameter
property |
description |
status
|
the request's HTTP error code (200 = OK, etc.)
|
statusText
|
HTTP error code text
|
responseText
|
the entire text of the fetched file, as a String
|
responseXML
|
the entire contents of the fetched file, as a DOM tree (seen later)
|
function handleRequest(ajax) {
alert(ajax.responseText);
}
- most commonly used property is
responseText
, to access the fetched text content
XMLHttpRequest
security restrictions
- cannot be run from a web page stored on your hard drive
- can only be run on a web page stored on a web server
- can only fetch files from the same site that the page is on
http://www.foo.com/a/b/c.html
can only connect to www.foo.com
Handling Ajax errors
new Ajax.Request("url",
{
method: "get",
onSuccess: functionName,
onFailure: ajaxFailure,
onException: ajaxFailure
}
);
...
function ajaxFailure(ajax, exception) {
alert("Error making Ajax request:" +
"\n\nServer status:\n" + ajax.status + " " + ajax.statusText +
"\n\nServer response text:\n" + ajax.responseText);
if (exception) {
throw exception;
}
}
- 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
Creating a POST
request
new Ajax.Request("url",
{
method: "post",
parameters: { name: value, name: value, ..., name: value },
onSuccess: functionName,
onFailure: functionName,
onException: functionName
}
);
method
should be changed to "post"
(or omitted; post
is default)
- any query parameters should be passed as a
parameters
parameter
- written between
{}
braces as a set of name : value pairs (another anonymous object)
get
request parameters can also be passed this way, if you like
Prototype's Ajax Updater
new Ajax.Updater("id", "url",
{
method: "get"
}
);
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
onSuccess
handler not needed (but onFailure
, onException
handlers may still be useful)
PeriodicalUpdater
new Ajax.PeriodicalUpdater("id", "url",
{
frequency: seconds,
name: value, ...
}
);
Ajax.PeriodicalUpdater
repeatedly fetches a file at a given interval and injects its content into an element as innerHTML
onSuccess
handler not needed (but onFailure
, onException
handlers may still be useful)
Ajax.Responders
Ajax.Responders.register(
{
onEvent: functionName,
onEvent: functionName,
...
}
);
- sets up a default handler for a given kind of event for all Ajax requests
- useful for attaching a common failure/exception handler to all requests in one place