Web Programming Step by Step, 2nd Edition

Lecture 21: Ajax

Reading: 12.1 - 12.2

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

Synchronous web communication

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

An aside: Creating a new anonymous object

var name = {
	fieldName: value,
	...
	fieldName: value
};
var pt = {
	x: 4,
	y: 3,
	distanceFromOrigin: function() {
		return Math.sqrt(this.x * this.x + this.y * this.y);
	}
};
alert(pt.x + ", " + pt.y + ", dist=" + pt.distanceFromOrigin());

Prototype's Ajax model

new Ajax.Request("url", {
	option : value,
	option : value,
	...
	option : value
});

Prototype Ajax options

option description
method how to fetch the request from the server (default "post")
asynchronous should request be sent asynchronously in the background? (default true)
parameters query parameters to pass to the server, if any (as a string or object)
onSuccess event: request completed successfully
onFailure event: request was unsuccessful
onException event: request has a syntax error, security error, etc.
others: contentType, encoding, requestHeaders; events: onCreate, onComplete, on### (for HTTP error code ###)

Prototype Ajax example

	new Ajax.Request("foo/bar/mydata.txt", {
		method: "get",
		onSuccess: myAjaxSuccessFunction
	});
	...

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

Ajax response object's properties

property description
status the request's HTTP result code (200 = OK, etc.)
statusText HTTP status code text
responseText the entire text of the fetched file, as a string
responseXML,
responseJSON
the entire contents of the fetched file, in other formats (seen later)
function myAjaxSuccessFunction(ajax) {
	alert(ajax.responseText);
}

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

Passing query parameters to a request

new Ajax.Request("lookup_account.php", {
	method: "get",
	parameters: {name: "Ed Smith", age: 29, password: "abcdef"},
	onFailure: ajaxFailure,
	onException: ajaxFailure
});
...

Creating a POST request

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

XMLHttpRequest security restrictions

Ajax security error

Prototype's Ajax Updater

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

Ajax.Updater options

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

PeriodicalUpdater

new Ajax.PeriodicalUpdater("id", "url", {
	frequency: seconds,
	name: value, ...
});

Ajax.Responders

Ajax.Responders.register({
	onEvent: functionName,
	onEvent: functionName,
	...
});