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.

Valid XHTML 1.1 Valid CSS!

Synchronous web communication (10.1)

synchronous communication

Web applications and Ajax

Ajax bleach

Asynchronous web communication

synchronous communication

XMLHttpRequest (and why we won't use it)

A typical Ajax request

request
  1. user clicks, invoking an event handler
  2. handler's code creates an XMLHttpRequest object
  3. XMLHttpRequest object requests page from server
  4. server retrieves appropriate data, sends it back
  5. XMLHttpRequest fires an event when data arrives
    • this is often called a callback
    • you can attach a handler function to this event
  6. 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
	}
);

Prototype Ajax methods and properties

options that can be passed to the Ajax.Request constructor
option description
method how to fetch the request from the server (default "post")
parameters query parameters to pass to the server, if any
asynchronous (default true), contentType, encoding, requestHeaders
events in the Ajax.Request object that you can handle
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 ###)

Basic Prototype Ajax template

	new Ajax.Request("url",
		{
			method: "get",
			onSuccess: functionName
		}
	);
	...

function functionName(ajax) {
	do something with ajax.responseText;
}

The Ajax response object

property description
status the request's HTTP error code (200 = OK, etc.)
statusText HTTP error code text
responseText the entire text of the fetched page, as a String
responseXML the entire contents of the fetched page, as an XML DOM tree (seen later)
function handleRequest(ajax) {
	alert(ajax.responseText);
}

XMLHttpRequest security restrictions

Ajax security error

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;
	}
}

Debugging Ajax code

Firebug Ajax

Creating a POST request

new Ajax.Request("url",
	{
		method: "post",   // optional
		parameters: { name: value, name: value, ..., name: value },
		onSuccess: functionName,
		onFailure: functionName,
		onException: functionName
	}
);

Prototype's Ajax Updater

	new Ajax.Updater(
		"id",
		"url",
		{
			method: "get"
		}
	);