User Tools

Site Tools


eg-259:emergency_lecture

~~SLIDESHOW~~

An Introduction to Ajax

Lecture 13: To be given on Thursday 13th November 2008.

Lecturer: Dr Chris P. Jobling.

Ajax is a reformulation of the DHTML idea that aims to make the user experience of interactive web applications more like the experience that they get with traditional desktop application. We introduce the Ajax idea and give a demonstration of its capabilities.

An Introduction to Ajax

“Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability.”1)

This lecture is based on Jesse James Garrett's original web article on Ajax2) with contributions from Zeldman 3) pp 112–113, Wikipedia 4)5)6)7), the critique to be found in the A List Apart article 8), and an on-line web tutorial [8].

Contents of this Lecture

Learning Outcomes

At the end of this lecture you should be able to answer these questions:

  • Define Ajax
  • What technologies does Ajax use?
  • How does the Ajax web differ from the classic web?
  • How does Ajax improve the user experience?

Learning Outcomes (more)

At the end of this lecture you should be able to answer these questions:

  • Who uses Ajax?
  • What is the Ajax engine?
  • What is JSON?
  • What advantage does an Ajax framework provide the web developer?

Acknowledgments

Jess James Garrett

  • This lecture is inspired by and based on Ajax: A New Approach to Web Applications by Jesse James Garrett (pictured) of Adaptive Path.9)
  • Additional notes are adapted from Wikipedia articles and other web sites which will be referenced in the slides.

In 2004 -- Before AJAX

  • User interaction with web clients was largely limited to the small number of controls provided by the HTML <form> element.
  • Comparatively, desktop applications, e.g. those created on Macintosh, Windows or with Java Swing, provided a much richer set of controls (widgets) and interface possibilities.
  • To create richer user experiences for a web user, web designers had to abandon standard HTML and use non-standard technologies like Flash.

Narrowing the Gap

  • In 2005 there were example web applications which illustrated that the gap between web application and desktop application was being narrowed. E.g. Google Suggest and Google Maps.
  • Google Suggest and Google Maps are examples of an approach to web applications that was termed Ajax by Jesse James Garrett and his colleagues at Adaptive Path.

Take a look at Google Suggest (http://www.google.com/webhp?complete=1&hl=en). Watch the way the suggested terms update as you type, almost instantly. Now look at Google Maps (http://maps.google.com/). Zoom in. Use your cursor to grab the map and scroll around a bit. Again, everything happens almost instantly, with no waiting for pages to reload.

What is Ajax?

  • Ajax is shorthand for Asynchronous JavaScript + XML
  • It “represents a fundamental shift in what's possible on the Web”
  • Not really a technology, not really new, rather a combination of existing technologies that together create a powerful new paradigm for web user interface design.

Defining Ajax

  • Standards-based presentation using XHTML and CSS;
  • Dynamic display and interaction using the Document Object Model;
  • Data interchange and manipulation using XML and XSLT;
  • Asynchronous data retrieval using XMLHttpRequest; and
  • JavaScript binding everything together.

We have of course already studied the first two and the last of these. XML and XSLT is only one way that data can be exchanged and manipulated. We will discuss XMLHttpRequest in due course.

The Classic Web

The classic web

The traditional model for web applications


The classic web application model works like this:

Most user actions in the interface trigger an HTTP request back to a web server. The server does some processing – retrieving data, crunching numbers, talking to various legacy systems – and then returns an HTML page to the client. It's a model adapted from the Web's original use as a hypertext medium, but what makes the Web good for hypertext doesn’t necessarily make it good for software applications.

This approach makes a lot of technical sense, but it doesn't make for a great user experience. While the server is doing its thing, what's the user doing? That's right, waiting. And at every step in a task, the user waits some more.

Obviously, if we were designing the Web from scratch for applications, we wouldn't make users wait around. Once an interface is loaded, why should the user interaction come to a halt every time the application needs something from the server? In fact, why should the user see the application go to the server at all?

How Ajax is Different

The Ajax web

The Ajax model for web applications


An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary – an Ajax engine – between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true.

Instead of loading a web page, at the start of the session, the browser loads an Ajax engine – written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user's behalf. The Ajax engine allows the user's interaction with the application to happen asynchronously – independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.

Synchronous Interaction

Synchronous interaction

The synchronous interaction pattern of a traditional web application

Asynchronous Interaction

Asynchronous interaction

The asynchronous pattern of an Ajax application


Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. Any response to a user action that doesn’t require a trip back to the server – such as simple data validation, editing data in memory, and even some navigation – the engine handles on its own. If the engine needs something from the server in order to respond – if it's submitting data for processing, loading additional interface code, or retrieving new data – the engine makes those requests asynchronously, usually using XML, without stalling a user’s interaction with the application.

Who's Using Ajax?


These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn't another technology that only works in a laboratory. And Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps.

The Ajax "Engine"

  • Relies on the non-standard XMLHttpRequest10) object introduced by Microsoft as an ActiveX control for Internet Explorer/Windows.
  • Available on most modern browsers, and being standardized by W3C11) but expect some variation between browser implementations
  • XMLHttpRequest is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.
  • The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text.

The "Renderers"

  • By default XMLHttpRequest returns XML
    • This can be manipulated as if it was a DOM object or further transformed with XSLT
  • It can also return a directly parsable text format called JSON12)
    • JSON (pronounced like the English given name Jason), which stands for “JavaScript Object Notation”, is a lightweight computer data interchange format.
    • JSON is a subset of the object literal notation of JavaScript but its use does not require JavaScript.

JSON is based on a subset of the JavaScript Programming Language. The format is specified in RFC 4627. The official MIME Media Type for JSON is application/json.

In JavaScript, JSON can be parsed trivially using the eval() procedure. This is important for the acceptance of JSON within the Ajax programming community because of JavaScript's ubiquity among web browsers.

A JSON Example

  • The following is a simple example of a menu definition. Note that the quoted text is an object literal:
    var myMenuText = '{
        "type": "menu",
        "value": "File",
        "items": [
            {"value": "New", "action": "CreateNewDoc"},
            {"value": "Open", "action": "OpenDoc"},
            {"value": "Close", "action": "CloseDoc"}
        ]
    }'
  • If this is returned from XMLHttpRequest, it can be evaluated and assigned to a reference by:
    var myMenuObject = eval(myMenuText); 

Function eval takes a string and evaluates as if it was JavaScript code. After evaluation, myMenuObject will be an object with properties type, value and items. Property items is a list (array) of objects each with properties value and action. The properties with pattern myMenu.items[n].action are presumably event handler functions.

Case Studies

Case Study 1

This case study is provided by the Mozilla Developer Center.13)

Step 1: Make an HTTP Request

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

Some versions of some Mozilla browsers won't work properly if the response from the server doesn't have an XML mime-type header. To satisfy this, you can use an extra method call to override the header sent by the server, just in case it's not text/xml.

httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');

Response handler

  • You need to decide what you want to do after you receive the server response to your request.
  • At this stage, you just need to tell the HTTP request object which JavaScript function will do the work of processing the response.
  • This is done by setting the onreadystatechange property of the object to the name of the JavaScript function you plan to use, like this:
    httpRequest.onreadystatechange = nameOfTheFunction; 

Note that there are no brackets after the function name and no parameters passed, because you're simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called “anonymous function”) and define the actions that will process the response right away, like this:

httpRequest.onreadystatechange = function(){
    // do the thing
};

Make the request

  • After you've declared what will happen as soon as you receive the response, you need to actually make the request.
  • You need to call the open() and send() methods of the HTTP request class, like this:
    httpRequest.open('GET', 'http://www.example.org/some.file', true);
    httpRequest.send(null);

The first parameter of the call to open() is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the W3C specs.

The second parameter is the URL of the page you're requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a 'permission denied' error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld.

The third parameter sets whether the request is asynchronous. If TRUE, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.

The parameter to the send() method can be any data you want to send to the server if POST-ing the request. The data should be in the form of a query string, like:

name=value&anothername=othervalue&so=on 

Note that if you want to POST data, you have to change the MIME type of the request using the following line:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Otherwise, the server will discard the POSTed data.

Step 2: Handling the Server Response

  • Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.
    httpRequest.onreadystatechange = nameOfTheFunction;
  • This function should have this structure:
    if (httpRequest.readyState == 4) {
       // everything is good, the response is received
    } else {
       // still not ready
    }

The function needs to check for the state of the request. If the state has the value of 4, that means that the full server response is received and it's OK for you to continue processing it.

The full list of the readyState values is as follows:

  0 (uninitialized) 
  1 (loading) 
  2 (loaded) 
  3 (interactive) 
  4 (complete) 

Check the status code of the HTTP server response

  • For our purposes we are only interested in 200 OK response.
    if (httpRequest.status == 200) {
        // perfect!
    } else {
        // there was a problem with the request,
        // for example the response may be a 404 (Not Found)
        // or 500 (Internal Server Error) response codes
   }

Do something with the response data

  • It's up to you to do whatever you want with the data the server has sent to you.
  • You have two options to access that data:
    • httpRequest.responseText – will return the server response as a string of text
    • httpRequest.responseXML – will return the response as an XMLDocument object you can traverse using the JavaScript DOM functions

Step 3: A Complete Example

  • Let's put it all together and do a simple HTTP request (httprequest_test.html).
  • Our JavaScript will request an HTML document, test.html, which contains the text “I'm a test.” and then we'll alert() the contents of the test.html file.

Step 4: Working with the XML Response

  • In the previous example, after the response to the HTTP request was received we used the responseText property of the request object, which contained the contents of the test.html file. Now let's try the responseXML property.
  • First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:
    <?xml version="1.0" ?>
    <root>
        I'm a test.
    </root>

Request line

  • In the script we only need to change the request line to:
    ...
    onclick="makeRequest('test.xml')">
    ...

alertContents()

  • Then in alertContents(), we need to replace the line alert(httpRequest.responseText); with:
   var xmldoc = httpRequest.responseXML;
   var root_node = xmldoc.getElementsByTagName('root').item(0);
   alert(root_node.firstChild.data);

This code takes the XMLDocument object given by responseXML and uses DOM methods to access some of the data contained in the XML document. You can see the test.xml here and the updated test script here.

<source http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/httprequest_test_xml.html javascript|httprequest_test_xml.html>

Case Study 2: Another Ajax Tutorial

  • This second case study is also on-line at tizag.com14)
  • It calls on a server script rather than a static file.
    <?php 
       echo date("H:i:s");
    ?>

Here is the code: <source http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/ajax.html javascript|ajax.html>

See the tutorial for a full explanation.

Case Study 3: Video

  • This screen cast “What is Ajax?” has been provided by Manning Publishers (to help to promote its book Ajax in Action)
  • It defines Ajax and shows an entertaining, working example of Ajax in action.
  • By gradually adding features, the screencast makes you think about the richness of your users' experience and shows you how it is done.
  • It is narrated by Marco Baringer, and is 18 minutes long (27MB download) [copy on Blacboard site].

Critique

Ajax in jQuery

<html> <object width=“425” height=“355”><param name=“movie” value=“http://www.youtube.com/v/XdUFjAvOPU0&rel=1&border=0”></param><param name=“wmode” value=“transparent”></param><embed src=“http://www.youtube.com/v/XdUFjAvOPU0&rel=1&border=0” type=“application/x-shockwave-flash” wmode=“transparent” width=“425” height=“355”></embed></object></html>

Further Reading

  • Despite its relative youth, there are many web sites and books that describe Ajax. In 2007, I counted in excess of 50 books on Amazon alone!
  • Three books that I actually own are:
    • Dave Crane, Eric Pascarello, and Darren James, Ajax in Action, Manning, 2005.
    • Brett McLaughlin, Head Rush Ajax, O'Reilly Media Inc., 2006
    • Justin Gehtland, Dion Almaer, and Ben Galbraith, Pragmatic Ajax: A Web 2.0 Primer, The Pragmatic Programmers, 2006.
  • The tutorial demonstrated in this lecture was provided by the Mozilla Developer Center.17) It takes you step by step through the use of XMLHttpRequest (including handling the browser incompatibilities) to create a simple Ajax application. If you want a hands-on introduction to Ajax, I suggest that you give it a try (see homework).

Summary of This Lecture

Learning Outcomes

At the end of this lecture you should be able to answer these questions:

  • Define Ajax
  • What technologies does Ajax use?
  • How does the Ajax web differ from the classic web?
  • How does Ajax improve the user experience?
  • Who uses Ajax?
  • What is the Ajax engine?
  • What is JSON?
  • What advantage does an Ajax framework provide the web developer?

Homework

What's Next?

Basic Web Server Operation

An introduction to server-side programming with a description of the operation of a basic webserver

  • The roles of a web server and web client
  • Modern Web Servers
  • Introducing the Apache Web Server
  • Revision of the HyperText Transfer Protocol (HTTP)
  • Web server operation
  • Mapping resources to files

Previous Lecture | home | Next Lecture


Here is the code: <source http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/httprequest_test.html javascript|httprequest_test.html>

In this example:

  • The user clicks the link “Make a request” in the browser;
  • This calls the makeRequest() function with a parameter – the name test.html of an HTML file in the same directory;
  • The request is made and then (onreadystatechange) the execution is passed to alertContents();
  • alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file.

See additional notes.

1) , 4)
Ajax (programming), Wikipedia, the free encyclopedia. URL: Ajax (programming).
2)
Jesse James Garrett, Ajax: A New Approach to Web Applications, Adaptive Path, February 18, 2005. URL: http://www.adaptivepath.com/publications/essays/archives/000385.php.
3)
Jeffery Zeldman, Designing with Web Standards, 2nd Edition, New Riders, 2007.
5) , 10)
XMLHttpRequest, Wikipedia, the free encyclopedia. URL: XMLHttpRequest.
6) , 12)
JSON, Wikipedia, Wikipedia, the free encyclopedia. URL: JSON.
7) , 16)
Ajax Framework, Wikipedia, the free encyclopedia. URL: Ajax framework
8) , 15)
Jeffrey Zeldman, “Web 3.0”, A List Apart, January 16, 2006. URL: http://www.alistapart.com/articles/web3point0.
9)
Adaptive Path is a Consultancy which specializes in improving the interaction between the web and people.
11)
The XMLHttpRequest Object, W3C Working Draft, 27 September 2006, URL: http://www.w3.org/TR/XMLHttpRequest/
13) , 17)
AJAX:Getting Started, Mozilla Developer Center, 12 September 2007. URL: http://developer.mozilla.org/en/docs/AJAX:Getting_Started.
14)
Ajax Tutorial, Tizag.com, URL: http://www.tizag.com/ajaxTutorial/index.php
eg-259/emergency_lecture.txt · Last modified: 2011/01/14 12:46 by 127.0.0.1