Web Programming Step by Step, 2nd Edition

Lecture 18: 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/ JSON data (AJAJ? ... seen next week)
  4. asynchronous w/ XML data (Ajax ... seen next week)

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?

There are two reasons a request might fail:

  1. The server responded to our request, but it sent an error message instead of the data we requested.

    (i.e., a server error occurred)

  2. The request was never even made to begin with, because either:
    • the browser security-blocked the request (to enforce the same-origin policy), or
    • there is no internet connection

    (i.e., a browser error occurred)

These two errors are handled differently.

Handling a server error

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 {  // any code other than 200 indicates an error message
		code to handle the server error;
	}
}

Handling a browser error

var ajax = new XMLHttpRequest();
ajax.onload = functionName;
ajax.onerror = browserErrorFunctionName;
ajax.open("GET", "url", true);
ajax.send();
...
function browserErrorFunctionName() {
	code to handle the browser error;
}

Full Ajax error handling example

var ajax = new XMLHttpRequest();
...
ajax.onerror = ajaxBrowserError;
ajax.onload = handleResponse;
...

function handleResponse() {
	if (this.status == 200) {  // 200 means request succeeded
		do something with this.responseText;
	} else {  // any code other than 200 indicates an error message
		alert('An Ajax error occurred!\n\n' +
		      'Error code: ' + this.status + '\n' +
		      'Error text: ' + this.statusText + '\n' +
		      'Full content of response:\n\n' + this.responseText);
	}
}

function ajaxBrowserError() {
	alert("An Ajax error occurred!\n\n" +
	      "The browser failed to contact the server. Either the browser " +
	      "security-blocked the request (to enforce the same-origin " +
	      "policy), or there is no internet connection.");
}

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