AJAX.ppt

25
AJAX AJAX (also known as: XMLHTTP, (also known as: XMLHTTP, Remote Scripting, Remote Scripting, XMLHttpRequest, etc.) XMLHttpRequest, etc.) Matt Warden

description

 

Transcript of AJAX.ppt

Page 1: AJAX.ppt

AJAXAJAX

(also known as: XMLHTTP, Remote (also known as: XMLHTTP, Remote Scripting, XMLHttpRequest, etc.)Scripting, XMLHttpRequest, etc.)

Matt Warden

Page 2: AJAX.ppt

What is AJAX?What is AJAX?

AAsynchronous synchronous JJavaScript avaScript aand nd XXML (or, ML (or, AAsynchronous synchronous JaJavaScript and vaScript and XXML)ML)

So, like LAMP, AJAX is not a technology So, like LAMP, AJAX is not a technology or language but rather a or language but rather a groupgroup of of technologiestechnologies

Allows for the creation of Allows for the creation of fat-clientfat-client web web applicationsapplications

Sound familiar to anyone?Sound familiar to anyone?

Page 3: AJAX.ppt

Reinventing the WheelReinventing the Wheel

Jesse James GarrettJesse James Garrett A WheelA Wheel

Page 4: AJAX.ppt

AJAX is Not NewAJAX is Not New

Active use for at least six yearsActive use for at least six years Was only available in IE (since IE5 public Was only available in IE (since IE5 public

preview in 1999) until about three years preview in 1999) until about three years ago, in Mozilla (versions just before 1.0)ago, in Mozilla (versions just before 1.0)

Primarily referred to as ‘XMLHTTP’Primarily referred to as ‘XMLHTTP’ This fact has brought Garrett criticismThis fact has brought Garrett criticism

Page 5: AJAX.ppt

Garrett’s ResponseGarrett’s Response

““What’s new is the prominent use of these What’s new is the prominent use of these techniques in real-world applications to change techniques in real-world applications to change the fundamental interaction model of the Web. the fundamental interaction model of the Web. Ajax is taking hold now because these Ajax is taking hold now because these technologies and the industry’s understanding technologies and the industry’s understanding of how to deploy them most effectively have of how to deploy them most effectively have taken time to develop.”taken time to develop.”

Buzzword Count = 10 Buzzword Count = 10 Nothing new Nothing new Back to AJAX…Back to AJAX…

Page 6: AJAX.ppt

Traditional vs. AJAXTraditional vs. AJAX

Interface construction is Interface construction is mainly the responsibility mainly the responsibility of the serverof the server

User interaction via form User interaction via form submissionssubmissions

An entire page is An entire page is required for each required for each interaction (bandwidth)interaction (bandwidth)

Application is Application is unavailable while an unavailable while an interaction is processing interaction is processing (application speed)(application speed)

Interface is manipulated Interface is manipulated by client-side JavaScript by client-side JavaScript manipulations of the manipulations of the Document Object Model Document Object Model (DOM)(DOM)

User interaction via User interaction via HTTP requests ‘behind HTTP requests ‘behind the scenes’the scenes’

Communication can be Communication can be restricted to data onlyrestricted to data only

Application is always Application is always responsiveresponsive

Page 7: AJAX.ppt

AJAX ExampleAJAX Example

Tom Riddle's Magical Diary Come to LifeTom Riddle's Magical Diary Come to Life

Page 8: AJAX.ppt

Other AJAX ExamplesOther AJAX Examples

Google’s GMailGoogle’s GMail Google SuggestGoogle Suggest Google Maps (sort of)Google Maps (sort of) FlickrFlickr

Page 9: AJAX.ppt

AJAX Details: XMLHTTPAJAX Details: XMLHTTP

An interface allows for the HTTP An interface allows for the HTTP communication without a page refreshcommunication without a page refresh

In IE, it is named XMLHTTP and In IE, it is named XMLHTTP and available as an ActiveX Objectavailable as an ActiveX Object

Mozilla and others then modeled a native Mozilla and others then modeled a native object called XMLHttpRequest after IE’s object called XMLHttpRequest after IE’s ActiveX ObjectActiveX Object

(The ‘others’ are Safari 1.2+, Opera 8+, (The ‘others’ are Safari 1.2+, Opera 8+, and Konqueror)and Konqueror)

Page 10: AJAX.ppt

XMLHTTP MethodsXMLHTTP Methods

abort()abort() Aborts a request.Aborts a request.

open(method, uri, open(method, uri, [async, [username, [async, [username, [password]]])[password]]])

Sets properties of Sets properties of request (does not request (does not send). (Note about send). (Note about async.)async.)

send(content)send(content) Sends the request with Sends the request with content in the body. content in the body. content should be null content should be null unless method is ‘post’.unless method is ‘post’.

Page 11: AJAX.ppt

XMLHTTP PropertiesXMLHTTP Properties

onreadystatechangeonreadystatechange Function obj to handle request Function obj to handle request progress.progress.

readyStatereadyState Read only. Current request progress.Read only. Current request progress.

responseTextresponseText Read only. esponse body as string.Read only. esponse body as string.

responseXMLresponseXML Read only. Response body parsed as Read only. Response body parsed as text/xml and in DOM Document obj.text/xml and in DOM Document obj.

statusstatus Read only. HTTP response status Read only. HTTP response status code.code.

Page 12: AJAX.ppt

Instantiating XMLHTTPInstantiating XMLHTTPfunction getXMLHTTP() {function getXMLHTTP() { var req = false;var req = false; if(window.XMLHttpRequest) {if(window.XMLHttpRequest) { try {try { req = new XMLHttpRequest();req = new XMLHttpRequest(); }} catch(e) {}catch(e) {} }} else if(window.ActiveXObject) {else if(window.ActiveXObject) { try {try { req = new ActiveXObject("Msxml2.XMLHTTP");req = new ActiveXObject("Msxml2.XMLHTTP"); }} catch(e) {catch(e) { try {try { req = new ActiveXObject("Microsoft.XMLHTTP");req = new ActiveXObject("Microsoft.XMLHTTP"); }} catch(e) {}catch(e) {} }} } // end if} // end if return req;return req;} // end function} // end function

Page 13: AJAX.ppt

Instantiating XMLHTTPInstantiating XMLHTTP

var request = getXMLHTTP();var request = getXMLHTTP();

request.onreadystatechange = handleReadyStateChange;request.onreadystatechange = handleReadyStateChange;

request.open(‘get’,‘/bar/checkuname.php?u=jessica’);request.open(‘get’,‘/bar/checkuname.php?u=jessica’);

request.send(null);request.send(null);

Page 14: AJAX.ppt

Handling ResponsesHandling Responses

function handleReadyStateChange() {function handleReadyStateChange() { if (!request) return;if (!request) return; // ignore unless complete readyState// ignore unless complete readyState if (request.readyState == 4) {if (request.readyState == 4) { // Ignore unless successful.// Ignore unless successful. if (request.status == 200) {if (request.status == 200) { // act on the response// act on the response var xmlbody = request.responseXML;var xmlbody = request.responseXML; // the line below is important!// the line below is important! request = false;request = false; processResponse(xmlbody);processResponse(xmlbody); }} }}} // end function} // end function

Page 15: AJAX.ppt

Example Response XMLExample Response XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><?xml version="1.0" encoding="UTF-8" standalone="yes"?><usernameresult><usernameresult> <username value="jessica" available="false" /><username value="jessica" available="false" /> <usernamealts><usernamealts> <username value="jess" available="true" /><username value="jess" available="true" /> <username value="jessica2005" available="true" /><username value="jessica2005" available="true" /> <username value="jessie" available="true" /><username value="jessie" available="true" /> </usernamealts></usernamealts></usernameresult></usernameresult>

• Requested username is unavailable, but Requested username is unavailable, but the script has determined some the script has determined some alternatives.alternatives.

Page 16: AJAX.ppt

Acting on a ResponseActing on a Response

JavaScript’s alert() function? You could JavaScript’s alert() function? You could use this, but it’s annoying and quite use this, but it’s annoying and quite defeats one of the reasons to use AJAX: defeats one of the reasons to use AJAX: allowing the application to always remain allowing the application to always remain responsive.responsive.

A better choice is to manipulate the DOM A better choice is to manipulate the DOM with JavaScript.with JavaScript.

Page 17: AJAX.ppt

Manipulating the DOMManipulating the DOMfunction processResponse(oXML) {function processResponse(oXML) { if (!oXML) return;if (!oXML) return; if (!oXML.documentElement) return;if (!oXML.documentElement) return; var doc = oXML.documentElement;var doc = oXML.documentElement; // return a nodeList of all username elements // return a nodeList of all username elements var unames = doc.getElementsByTagName('username');var unames = doc.getElementsByTagName('username'); var msgs = new Array();var msgs = new Array(); // iterate through the username nodeList// iterate through the username nodeList for (var i=0; i<unames.length; i++) {for (var i=0; i<unames.length; i++) { var u = unames.item(i);var u = unames.item(i); var username = u.getAttribute('value');var username = u.getAttribute('value'); var availability = u.getAttribute('available');var availability = u.getAttribute('available'); // make the available attribute more user-friendly// make the available attribute more user-friendly if (availability == 'true') {if (availability == 'true') { availability = 'available';availability = 'available'; }} else {else { availability = 'not available';availability = 'not available'; }} msgs[msgs.length] = 'Username '+ username msgs[msgs.length] = 'Username '+ username +' is '+ availability;+' is '+ availability; }}

Page 18: AJAX.ppt

processResponse Cont’dprocessResponse Cont’d // create an unordered list element// create an unordered list element ul = document.createElement('ul');ul = document.createElement('ul'); ul.id = 'msg';ul.id = 'msg'; // for each message, create a list item// for each message, create a list item // element and a text node containing // element and a text node containing // the message. The text node is a child// the message. The text node is a child // node of the list item element, and the// node of the list item element, and the // the list item is a child node of the // the list item is a child node of the // unordered list element.// unordered list element. for (var k=0; k<msgs.length; k++) {for (var k=0; k<msgs.length; k++) { var li = document.createElement('li');var li = document.createElement('li'); var txt = document.createTextNode(msgs[k]);var txt = document.createTextNode(msgs[k]); li.appendChild(txt);li.appendChild(txt); ul.appendChild(li);ul.appendChild(li); }} // obtain a reference to the maindiv element// obtain a reference to the maindiv element // and insert our new unordered list just before it// and insert our new unordered list just before it var maindiv = document.getElementById('maindiv');var maindiv = document.getElementById('maindiv'); maindiv.parentNode.insertBefore(ul,maindiv);maindiv.parentNode.insertBefore(ul,maindiv);}}

Page 19: AJAX.ppt

Altered DOM After Altered DOM After ManipulationManipulation

…… parentNodeparentNode

ulul lili

Username jessica is not availableUsername jessica is not available Username jess is availableUsername jess is available Username jessica2005 is availableUsername jessica2005 is available Username jessie is availableUsername jessie is available

maindivmaindiv ……

Page 20: AJAX.ppt

This is a working exampleThis is a working example You can see it in action and view all You can see it in action and view all

source at source at http://mwarden.f2o.org/sandbox/http://mwarden.f2o.org/sandbox/......

(Note that the server portion of the code (Note that the server portion of the code is static, so it is only a demonstration of is static, so it is only a demonstration of how AJAX works, not a working how AJAX works, not a working application.)application.)

Page 21: AJAX.ppt

AJAX LibrariesAJAX Libraries

SAJAXSAJAX Makes things marginally easierMakes things marginally easier Doesn’t support XML responsesDoesn’t support XML responses uses innerHTML, so can’t even use DOMuses innerHTML, so can’t even use DOM

CPAINTCPAINT Supports XML and text responsesSupports XML and text responses Actively developed and matureActively developed and mature Documentation a little immatureDocumentation a little immature

JPSPANJPSPAN Excellent abstractionExcellent abstraction Seamlessly “imports” server-side objects into JavaScriptSeamlessly “imports” server-side objects into JavaScript Clear documentationClear documentation Doesn’t support OperaDoesn’t support Opera Limited usefulnessLimited usefulness

Page 22: AJAX.ppt

When Not to Use AJAXWhen Not to Use AJAX

Jesse James Garrett says:Jesse James Garrett says: ““We don’t know yet [for what types of We don’t know yet [for what types of

applications AJAX is best suited]. applications AJAX is best suited]. Because this is a relatively new Because this is a relatively new approach, our understanding of where approach, our understanding of where Ajax can best be applied is still in its Ajax can best be applied is still in its infancy. Sometimes the traditional web infancy. Sometimes the traditional web application model is the most appropriate application model is the most appropriate solution to a problem.”solution to a problem.”

Page 23: AJAX.ppt

When Not to Use AJAXWhen Not to Use AJAX

““We” don’t know, but I might.We” don’t know, but I might. In my opinion, it’s quite clear when AJAX In my opinion, it’s quite clear when AJAX

is not appropriate.is not appropriate. Importance Application stateImportance Application state

Back buttonBack button BookmarkingBookmarking

Sounds a lot like well-known misuses of Sounds a lot like well-known misuses of Flash!Flash!

Page 24: AJAX.ppt

A Rule of ThumbA Rule of Thumb

AJAX is good for making web-based AJAX is good for making web-based versions of traditionally desktop versions of traditionally desktop applicationsapplications

AJAX opens up AJAX opens up newnew possibilities for web possibilities for web apps, but does not necessarily benefit apps, but does not necessarily benefit traditional possibilitiestraditional possibilities

If you need serious workarounds to bring If you need serious workarounds to bring usability up to expected levels, you’re usability up to expected levels, you’re probably misusing AJAX.probably misusing AJAX.

Page 25: AJAX.ppt

Further InformationFurther Information

http://http://developer.apple.com/internet/webcontent/xmlhttpreq.htdeveloper.apple.com/internet/webcontent/xmlhttpreq.htmlml

http://http://en.wikipedia.org/wiki/XMLHttpRequesten.wikipedia.org/wiki/XMLHttpRequest http://en.wikipedia.org/wiki/AJAXhttp://en.wikipedia.org/wiki/AJAX http://http://

xulplanet.com/references/objref/XMLHttpRequest.htmlxulplanet.com/references/objref/XMLHttpRequest.html http://http://www.mozilla.org/xmlextraswww.mozilla.org/xmlextras// http://http://www.ajaxpatterns.orgwww.ajaxpatterns.org// http://www.ajaxmatters.com/http://www.ajaxmatters.com/

Questions?Questions?