~~SLIDESHOW~~ ====== An Introduction to Ajax ====== **Lecture 13**: To be given on Thursday 13th November 2008. **Lecturer**: [[C.P.Jobling@Swansea.ac.uk|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."((Ajax (programming), Wikipedia, the free encyclopedia. URL: [[wp>Ajax (programming)|Ajax (programming)]].)) ---- This lecture is based on Jesse James Garrett's original web article on Ajax((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.)) with contributions from Zeldman ((Jeffery Zeldman, Designing with Web Standards, 2nd Edition, New Riders, 2007.)) pp 112--113, Wikipedia ((Ajax (programming), Wikipedia, the free encyclopedia. URL: [[wp>Ajax (programming)|Ajax (programming)]].))((''XMLHttpRequest'', Wikipedia, the free encyclopedia. URL: [[wp>XMLHttpRequest]].))((JSON, Wikipedia, Wikipedia, the free encyclopedia. URL: [[wp>JSON]].))((Ajax Framework, Wikipedia, the free encyclopedia. URL: [[wp>Ajax_framework|Ajax framework]])), the critique to be found in the //A List Apart// article ((Jeffrey Zeldman, "Web 3.0", //A List Apart//, January 16, 2006. URL: http://www.alistapart.com/articles/web3point0.)), and an on-line web tutorial [8]. ===== Contents of this Lecture ===== An introduction to AJAX * [[eg-259:lecture12#three_year_s_ago|Introduction]] * [[eg-259:lecture12#defining_ajax|Defining Ajax]] * [[eg-259:lecture12#how_ajax_is_different|How Ajax is Different]] * [[eg-259:lecture12#who_s_using_ajax|Who's Using Ajax?]] * [[eg-259:lecture12#case_studies|Case Studies]] * [[eg-259:lecture12#critique|Critique]] * [[eg-259:lecture12#ajax_in_jquery|Ajax in jQuery]] (video) ===== 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 ===== {{ eg-259:headshot_garrett.jpg|Jess James Garrett}} * This lecture is inspired by and based on [[http://www.adaptivepath.com/ideas/essays/archives/000385.php|Ajax: A New Approach to Web Applications]] by Jesse James Garrett (pictured) of Adaptive Path.((Adaptive Path is a Consultancy which specializes in improving the interaction between the web and people.)) * 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 ''
'' 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. [[http://www.google.com/webhp?complete=1&hl=en|Google Suggest]] and [[http://maps.google.com/|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 [[http://www.google.com/webhp?complete=1&hl=en|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 [[http://maps.google.com/|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 **A**synchronous **Ja**vaScript + **X**ML * 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 ===== {{eg-259:ajax-fig1-left.png|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 ===== {{eg-259:ajax-fig1-right.png|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 ===== {{eg-259:ajax-fig2-top.png|Synchronous interaction}} //The synchronous interaction pattern of a traditional web application// ===== Asynchronous Interaction ===== {{eg-259:ajax-fig2-bottom.png|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? ===== * Google is making a large investment in Ajax: [[http://www.orkut.com/|Orkut]], [[http://www.gmail.com/|Gmail]], [[http://www.google.com/calendar|Google Calendar]], [[http://groups-beta.google.com/|Google Groups]], [[http://docs.google.com/|Google Docs]], [[http://www.google.com/webhp?complete=1&hl=en|Google Suggest]] and [[http://maps.google.com/|Google Maps]] are all examples of Ajax applications. * Many features that make [[http://www.flickr.com/|Flickr]], Amazon's [[http://a9.com/|A9.com]], [[http://del.icio.us|del.icio.us]] and [[http://www.facebook.com/|Facebook]] popular also rely on Ajax. * Ajax is an important part of the strategy underlying [[http://get.live.com/|Windows Live]] and [[http://www.yahoo.com/|Yahoo!]] ---- 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 ''XMLHttpRequest''((''XMLHttpRequest'', Wikipedia, the free encyclopedia. URL: [[wp>XMLHttpRequest]].)) object introduced by Microsoft as an ActiveX control for Internet Explorer/Windows. * Available on most modern browsers, and being standardized by W3C((The ''XMLHttpRequest'' Object, W3C Working Draft, 27 September 2006, URL: http://www.w3.org/TR/XMLHttpRequest/)) 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 JSON((JSON, Wikipedia, Wikipedia, the free encyclopedia. URL: [[wp>JSON]].)) * 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 [[http://www.faqs.org/rfcs/rfc4627.html|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|Case Study 1]]: Getting Started with Ajax * [[#case_study_2another_ajax_tutorial|Case Study 2]]: Another Ajax Tutorial * [[#case_study_3video|Case Study 3]]: Video ===== Case Study 1 ===== This [[http://developer.mozilla.org/en/docs/AJAX:Getting_Started|case study]] is provided by the Mozilla Developer Center.((AJAX:Getting Started, Mozilla Developer Center, 12 September 2007. URL: http://developer.mozilla.org/en/docs/AJAX:Getting_Started.)) * Step 1: [[#step_1make_an_http_request|Make an HTTP Request]] * Step 2: [[#step_2handling_the_server_response|Handling the Server Response]] * Step 3: [[#step_3a_complete_example|A Complete Example]] * Step 4: [[#step_4working_with_the_xml_response|Working with the XML Response]] ===== 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 ([[http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/httprequest_test.html|httprequest_test.html]]). * Our JavaScript will request an HTML document, [[http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/test.html|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 [[http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/test.html|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 ([[http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/test.xml|test.xml]]) contains the following: I'm a test. ===== 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 [[http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/test.xml|test.xml]] here and the updated test script [[http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/httprequest_test_xml.html|here]]. ===== Case Study 2: Another Ajax Tutorial ===== * This second case study is also on-line at [[http://www.tizag.com/ajaxTutorial/index.php|tizag.com]]((Ajax Tutorial, Tizag.com, URL: http://www.tizag.com/ajaxTutorial/index.php)) * It calls on a server script rather than a static file. * Here is the example: [[http://eehope.swan.ac.uk/~eechris/eg-259/examples/lecture12/ajax.html|ajax.html]] ---- Here is the code: See the [[http://www.tizag.com/ajaxTutorial/index.php|tutorial]] for a full explanation. ===== Case Study 3: Video ===== * This screen cast "What is Ajax?" has been provided by [[http://www.manning.com/crane/|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]. * You will need Apple's [[http://www.quicktime.com/|Quicktime 7]] to view the video. If you have iTunes, you probably already have Quicktime. If not, it is a free download, from http://www.quicktime.com/. ===== Critique ===== * Like many Web technologies that preceded it, Ajax is subject to large amounts of hype((Jeffrey Zeldman, "Web 3.0", //A List Apart//, January 16, 2006. URL: http://www.alistapart.com/articles/web3point0.)) * It produces nice user experiences at the cost of increased complexity for developers * Prepackaged Ajax components, JavaScript libraries and Ajax Frameworks((Ajax Framework, Wikipedia, the free encyclopedia. URL: [[wp>Ajax_framework|Ajax framework]])) are emerging * These aim to reduce the complexity by encouraging the use of existing web application development techniques. * Some examples: [[http://code.google.com/webtoolkit/|Google Web Toolkit (GWT)]], [[http://dojotoolkit.org/|dojo]], [[http://www.prototypejs.org/|prototype]], [[http://script.aculo.us/|script.aculo.us]], [[http://developer.yahoo.com/yui/|Yahoo! User Interface Library (YUI)]], [[http://jquery.com/|jQuery]]. ===== Ajax in jQuery ===== * From [[http://15daysofjquery.com/quick-and-dirty-ajax/14/|Quick and Dirty Ajax]] from the [[http://15daysofjquery.com/|15 Days of jQuery]] blog by Jack Born. * Video (from [[http://www.youtube.com/watch?v=XdUFjAvOPU0|YouTube]]): ===== 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 [[http://developer.mozilla.org/en/docs/AJAX:Getting_Started|tutorial]] demonstrated in this lecture was provided by the Mozilla Developer Center.((AJAX:Getting Started, Mozilla Developer Center, 12 September 2007. URL: http://developer.mozilla.org/en/docs/AJAX:Getting_Started.)) 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 ===== An introduction to AJAX * [[eg-259:lecture12#three_year_s_ago|Introduction]] * [[eg-259:lecture12#defining_ajax|Defining Ajax]] * [[eg-259:lecture12#how_ajax_is_different|How Ajax is Different]] * [[eg-259:lecture12#who_s_using_ajax|Who's Using Ajax?]] * [[eg-259:lecture12#case_studies|Case Studies]] * [[eg-259:lecture12#critique|Critique]] * [[eg-259:lecture12#ajax_in_jquery|Ajax in jQuery]] ===== 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 ===== * Acquire and read the Wikipedia and web articles referenced in the wiki page. * Work through the [[http://developer.mozilla.org/en/docs/AJAX:Getting_Started|Mozilla Developer Center tutorial]] presented as [[#case_study_1|Case Study 1]]. * Work through the [[http://www.tizag.com/ajaxTutorial/index.php|Tizag.com Ajax Tutorial]] presented as [[#case_study_2another_ajax_tutorial|Case Study 2]]. * Watch the videos mentioned in [[#case_study_2video|Case Study 3]] and [[#ajax_in_jquery|Ajax in jQuery]]. Make notes on the differences. * Evaluate any of the available Ajax frameworks mentioned in the [[#critique|critique]]. ===== 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 [[eg-259:lecture11|Previous Lecture]] | [[eg-259:home]] | [[eg-259:lecture14|Next Lecture]] ---- Here is the code: 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 [[http://developer.mozilla.org/en/docs/AJAX:Getting_Started#Step_3_.E2.80.93_.22All_together_now.21.22_-_A_Simple_Example|notes]].