Web Programming Step by Step, 2nd Edition

Lecture 22: 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

The XMLHttpRequest object

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

Levels of using XMLHttpRequest

  1. synchronized, text/HTML-only (SJAT?)
  2. asynchronous, text/HTML-only (AJAT?)
  3. asynchronous w/ XML data (Ajax ... seen next lecture)

XMLHttpRequest methods

the core JavaScript object that makes Ajax possible

Method Description
open(method, url, async) specifies the URL and HTTP request method
send()
send(postData)
sends the HTTP request to the server, with optional POST parameters
abort() stops the request
getAllResponseHeaders(),
getResponseHeader(name),
setRequestHeader(name, value)
for getting/setting raw HTTP headers

XMLHttpRequest properties

Property Description
responseText the entire text of the fetched page, as a string
responseXML the entire contents of the fetched page, as an XML document tree (seen later)
status the request's HTTP status code (200 = OK, etc.)
statusText HTTP status code text (e.g. "Bad Request" for 400)
timeout how many MS to wait before giving up and aborting the request (default 0 = wait forever)
readyState request's current state (0 = not initialized, 1 = set up, 2 = sent, 3 = in progress, 4 = complete)

1. Synchronized requests (bad)

// this code is in some control's event handler
var ajax = new XMLHttpRequest();
ajax.open("GET", url, false);
ajax.send();
do something with ajax.responseText;

Why synchronized requests suck

XMLHttpRequest events

Event Description
load occurs when the request is completed
error occurs when the request fails
timeout occurs when the request times out
abort occurs when the request is aborted by calling abort()
loadstart, loadend,
progress, readystatechange
progress events to track a request in progress

2. Asynchronous requests, basic idea

var ajax = new XMLHttpRequest();
ajax.onload = functionName;
ajax.open("GET", url, true);
ajax.send();
...
function functionName() {
	do something with this.responseText;
}

What if the request fails?

var ajax = new XMLHttpRequest();
ajax.onload = functionName;
ajax.open("GET", "url", true);
ajax.send();
...
function functionName() {
	if (this.status == 200) {   // 200 means request succeeded
		do something with this.responseText;
	} else {
		code to handle the error;
	}
}

Handling the error event

var ajax = new XMLHttpRequest();
ajax.onload = functionName;
ajax.onerror = errorFunctionName;
ajax.open("GET", "url", true);
ajax.send();
...
function functionName(e) {
	do something with e, this.status, this.statusText, ...
}

Example Ajax error handler

var ajax = new XMLHttpRequest();
...
ajax.onerror = ajaxFailure;
...

function ajaxFailure(exception) {
	alert("Error making Ajax request:" + 
	      "\n\nServer status:\n" + this.status + " " + this.statusText + 
	      "\n\nServer response text:\n" + this.responseText);
	if (exception) {
		throw exception;
	}
}

Debugging Ajax code

Firebug Ajax

Passing query parameters to a request

var ajax = new XMLHttpRequest();
ajax.onload = functionName;
ajax.open("GET", "url?name1=value1&name2=value2&...", true);
ajax.send();

Creating a POST request

var params = new FormData();
params.append("name", value);
params.append("name", value);

var ajax = new XMLHttpRequest();
ajax.onload = functionName;
ajax.open("POST", "url", true);
ajax.send(params);

XMLHttpRequest security restrictions

Ajax security error