Asynchronous Javascript + XML (Ajax)

CSE 190 M (Web Programming), Spring 2007

University of Washington

References: w3schools, Wikipedia

Except where otherwise noted, the contents of this presentation are © Copyright 2007 Marty Stepp and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.0 Strict Valid CSS!

Web data

URLs and web servers

http://server/path/file

Query strings

http://www.google.com/search?q=colbert&ie=utf-8

Web data example

What is Ajax?

Web applications

Quick Ajax example

Core Ajax concepts

A typical Ajax request

request

Asynchronous communication

synchronous communication asynchronous communication

Ajax communication flow

web page flow ajax flow

The XMLHttpRequest object

Usage of XMLHttpRequest

// this code is in some onscreen control's event handler
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function;
ajax.open("GET", url, true);
ajax.send(null);

The readyState property

Ajax XMLHttpRequest template

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
    if (ajax.readyState == 4) {
        do something with ajax.responseText;
    }
};
ajax.open("GET", url, true);
ajax.send(null);

What if the request fails?

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
    if (ajax.readyState == 4) {
        if (ajax.status == 200) {
            do something with ajax.responseText;
        } else {
            code to handle the error;
        }
    }
};
ajax.open("GET", url, true);
ajax.send(null);

XMLHttpRequest security restrictions

Ajax security error

Practice problem: ASCIImation viewer