~~SLIDESHOW~~
Contact Hour 16: To be discussed on Wednesday 7th March 2012.
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.
“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 session 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].
An introduction to AJAX
At the end of this lecture you should be able to answer these questions:
At the end of this lecture you should be able to answer these questions:
<form>
element. Take a look at Google Search (http://www.google.com/). 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.
XMLHttpRequest
; and
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 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?
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.
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.
Short answer … everyone!
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.
XMLHttpRequest
10) object introduced by Microsoft as an ActiveX control for Internet Explorer/Windows. 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.
<note>
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.
</note>
XMLHttpRequest
returns XML<note>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. </note>
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.
var myMenuText = '{ "type": "menu", "value": "File", "items": [ {"value": "New", "action": "CreateNewDoc"}, {"value": "Open", "action": "OpenDoc"}, {"value": "Close", "action": "CloseDoc"} ] }'
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.
This case study is provided by the Mozilla Developer Center.14)
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');
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 };
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 resource you're requesting.
<note warn>
You cannot access resources from 3rd-party domains. This is called cross site scripting (XSS) Cross-site_scripting and is not allowed as a security feature. 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 mistake is accessing your site by domain.tld, but attempting to get resources with www.domain.tld.
</note>
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.
httpRequest.onreadystatechange = nameOfTheFunction;
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)
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 }
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 alert()
the contents of the test.html file.<source http://eng-hope.swan.ac.uk/eg-259/examples/lecture12/httprequest_test.html javascript|httprequest_test.html>
In this example:
makeRequest()
function with a parameter – the name test.html of an HTML file in the same directory;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.
responseText
property of the request object, which contained the contents of the test.html file. Now let's try the responseXML
property.<?xml version="1.0" ?> <root> I'm a test. </root>
... onclick="makeRequest('test.xml')"> ...
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://eng-hope.swan.ac.uk/eg-259/examples/lecture12/httprequest_test_xml.html javascript|httprequest_test_xml.html>
<?php echo date("H:i:s"); ?>
Here is the code: <source http://eng-hope.swan.ac.uk/eg-259/examples/lecture12/ajax.html javascript|ajax.html>
See the tutorial for a full explanation.
Here is the code: <source http://eng-hope.swan.ac.uk/eg-259/examples/lecture12/ajax_jq.html javascript|ajax_jq.html>
<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>
One of the standards being developed in HTML5 is a new JavaScript API called web sockets. This may eventually replace AJAX and become the standard method of providing long-lived data communications between web browsers and web servers. It is supported now by Google Chrome and Safari.
Find out more visit:
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). An introduction to AJAX
At the end of this lecture you should be able to answer these questions:
This ends Part 2: Server Side Programming. There is some additional material that was used last year but removed from the module this year that you may wish to look at.
You'll find it on Blackboard and on this wiki as Record of Courses Pre-2012.
Basic Web Server Operation
An introduction to server-side programming with a description of the operation of a basic webserver
XMLHttpRequest
Object, W3C Working Draft, 27 September 2006, URL: http://www.w3.org/TR/XMLHttpRequest/