!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Lecture 19
AJAX and AJAX-based Web Applications
Ketan Mayer-Patel
University of North Carolina, Chapel Hill
AJAX
- Asynchronous JavaScript and XML
- Originally invented to support interface actions that needed back-end information
- Overview
- Client-side JavaScript used to initiate an HTTP request
- Asynchronous
- Code used to initiate request does not wait for answer.
- Register handler to process result
- Notified at different stages of completion.
- Just another form of event-based programming
XHR
- XMLHTTPRequest Object (XHR)
- Standardized by W3C in 2007
- Lifecyle:
- Create the XHR - browser specific
- Set up onreadystatechange
- XHR property set to function for handling results
- Open - indicate the URL to be requested
- Send - initiate the request
onreadystatechange
- Called as request progresses through different stages.
- readyState
- XHR property that indicates state of request
- onreadystatechange handler called whenever this changes
- Stages:
- 0: XHR created but not initialized (i.e., before open)
- 1: Initialized, but request not yet sent.
- 2: Sent, but response not yet received.
- 3: Status received, but full response not yet ready.
- 4: Complete
Important XHR object properties
- status
- Returns 3-digit HTTP status code from response
- Allows handler to distinguish successful responses from errors
- responseText
- Body of HTTP response as a string
- responseXML
- If response was XML, then responseText is parsed into an XML DOM tree and stored here.
- NOTE: Completely separate DOM tree from document
An example
- This only works in Firefox
- Note wwwx server
Prototype AJAX
- Cross-browser compatible
- Ajax.Request object
new Ajax.Request(url, options)
Options
- Hash object
- method: 'post'
- Lots of callbacks
- onSuccess, onCreate, onComplete, onException, onFailure, onLoaded, onLoading,
- Most callbacks provided with an Ajax.Response object
Example in Prototye
MVC Web Applications
- Model-View-Controller
- Design pattern
- Model: Data and state of application
- Controller: Logic
- View: Interface
MVC Web Applications

Drawbacks
- Division between controller and view not always clean
- Some interface actions require information from the model
- Round-trip to server feels "clunky"
AJAX-based Architecture
- Move all logic and interface to the client-side
- Use AJAX for all communication with the server
- Server-side is now nothing but model.
- Expose model data as a set of "resources"
- Resources addressed by URL
- RESTful interface
- A particular convention/style for naming and addressing resources via URL
AJAX Web Applications
