<<

Web Programming Step by Step Chapter 10 and XML for Accessing Data

Exceptwhereotherwisenoted,thecontentsofthispresentationareCopyright2009MartySteppandJessica Miller.

10.1: Ajax Concepts

10.1: Ajax Concepts 10.2:Using XMLHttpRequest 10.3:XML Synchronous web communication (10.1)

synchronous :usermustwaitwhilenewpagesload thetypicalcommunicationpatternusedinwebpages(click,wait,refresh)

Web applications

:awebsitethatmimicsthelook,feel,andoveralluserexperienceofadesktop application awebapppresentsacontinuoususerexperienceratherthandisjointpages asmuchaspossible,"feels"likeanormalprogramtotheuser examplesofwebapps , Maps , GoogleDocsand , , A9 manywebappsuseAjaxtobattletheseproblemsofwebpages: slowness/lackofUIresponsiveness lackofuserfriendliness jarringnatureof"clickwaitrefresh"pattern What is Ajax?

Ajax :AsynchronousJavaScriptandXML

notaprogramminglanguage;aparticularwayofusingJavaScript downloadsdatafromainthebackground allowsdynamicallyupdatingapagewithoutmakingtheuserwait aidsinthecreationofrich,userfriendlywebsites examples:UW's CSE14xDiffTool , PracticeIt ; GoogleSuggest

Asynchronous web communication

asynchronous :usercankeepinteractingwithpagewhiledataloads communicationpatternmadepossiblebyAjax

Core Ajax concepts

JavaScript's XMLHttpRequest objectcanfetchfilesfromawebserver supportedinIE5+,,,(withminorcompatibilities) itcandothis asynchronously (inthebackground,transparenttouser) contentsoffetchedfilecanbeputintocurrentwebpageusingDOM result:user'swebpageupdatesdynamicallywithoutapagereload A typical Ajax request

1. userclicks,invokingeventhandler 2. thathandler'sJScodecreatesan XMLHttpRequest object 3. XMLHttpRequest objectrequestsadocumentfrom awebserver 4. serverretrievesappropriatedata,sendsitback 5. XMLHttpRequest fireseventtosaythatthedatahas arrived thisisoftencalleda callback youcanattachahandlertobenotifiedwhenthe datahasarrived 6. yourcallbackeventhandlerprocessesthedataanddisplaysit

10.2: Using XMLHttpRequest

10.1:AjaxConcepts 10.2: Using XMLHttpRequest 10.3:XML The XMLHttpRequest object

the core JavaScript object that makes Ajax possible

methods: abort , getAllResponseHeaders , getResponseHeader , open , send , setRequestHeader properties: onreadystatechange , readyState , responseText , responseXML , status , statusText IE6doesn'tfollowstandardsandusesitsown ActiveXObject instead we'lllearntouseAjaxin4steps: 1. synchronous,textonly(SJAT?) 2. asynchronous,textonly(AJAT?) 3. asynchronousw/Prototype(AJAP?) 4. asynchronousw/XMLdata(realAjax)

1. Synchronous requests (10.2.1) var ajax = new XMLHttpRequest(); ajax.open("GET", , false); ajax.send(null);

// at this point, the request will have returned with its data do something with ajax.responseText ;

createtherequestobject,openaconnection,sendtherequest when send returns,thefetchedtextwillbestoredinrequest's responseText property Why synchronous requests are bad

yourcodewaitsfortherequesttocompletelyfinish beforeproceeding easierforyoutoprogram,but... theuser's entire browser locks up untilthedownloadis completed aterribleuserexperience(especiallyifthefileisvery large)

2. Asynchronous requests, basic idea (10.2.3) var ajax = new XMLHttpRequest(); ajax.onreadystatechange = functionName ; ajax.open("get", url , true ); ajax.send(null);

// don't process ajax.responseText here, but in your function ...

attachaneventhandlertotherequest's onreadystatechange event pass true asthirdparameterto open handlerwillbecalledwhenrequeststatechanges,e.g.finishes function'scodewillberunwhenrequestiscomplete The readyState property

holdsthestatusofthe XMLHttpRequest possiblevaluesforthe readyState property: State Description 0 notinitialized 1 setup 2 sent 3 inprogress 4 complete readyState changes→ onreadystatechange handlerruns usuallyweareonlyinterestedin readyState of4(complete)

Asynchronous XMLHttpRequest template var ajax = new XMLHttpRequest(); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { // 4 means request is finished do something with ajax.responseText ; } }; ajax.open("get", url , true); ajax.send(null);

mostAjaxcodeusesan anonymous function astheeventhandler usefultodeclareitasaninneranonymousfunction,becausethenit canaccesssurroundinglocal variables (e.g. ajax ) Checking for request errors (10.2.2) var ajax = new XMLHttpRequest(); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { // 200 means request succeeded do something with ajax.responseText ; } else { code to handle the error ; } } }; ajax.open("get", url , true); ajax.send(null);

webserversreturn statuscodes forrequests(200meansSuccess) youmaywishtodisplayamessageortakeactiononafailedrequest

Prototype's Ajax model (10.2.4) new Ajax.Request( " url ", { option : value , option : value , ... option : value } );

Prototype's Ajax.Request objectconstructoraccepts2parameters: 1. the URL tofetch,asaString, 2. asetof options ,asanarrayof key :value pairsin {} braces hidessomeoftheickydetails( onreadystatechange ,etc.) worksinallbrowsers:IE,Firefox,etc. Prototype Ajax methods and properties

options thatcanbepassedtothe Ajax.Request constructor: method :howtofetchtherequestfromtheserver(default "" ) parameters :queryparameterstopasstotheserver,ifany asynchronous (default true ), contentType , encoding , requestHeaders eventsinthe Ajax.Request objectthatyoucanhandle: onSuccess :requestcompletedsuccessfully onFailure :requestwasunsuccessful onCreate , onComplete , onException , on### (handlerforHTTPerrorcode###)

Prototype Ajax template

new Ajax.Request( " url ", { method: "get", onSuccess: functionName } ); ... function functionName (ajax) { do something with ajax.responseText ; }

mostAjaxrequestswe'lldointhiscourseareGETrequests attachahandlertotherequest's onSuccess event thehandleracceptsthe XMLHttpRequest object, ajax ,asaparameter Handling Ajax errors w/ Prototype

new Ajax.Request( " url ", { method: "get", onSuccess: functionName , onFailure: ajaxFailure } ); ... function ajaxFailure(ajax) { alert("Error making Ajax request:" + "\n\nServer status:\n" + ajax.status + " " + ajax.statusText + "\n\nServer response text:\n" + ajax.responseText); }

foruser's(anddeveloper's)benefit,showamessageifarequestfails agoodfailuremessageshowstheHTTPerrorcodeandstatustext

Creating a POST request new Ajax.Request( " url ", { method: "POST", // optional parameters: { name : value , name : value , ..., name : value }, onSuccess: functionName , onFailure: functionName } );

Ajax.Request canalsobeusedtopostdatatoawebserver method shouldbechangedto "post" (oromitted; post isdefault) anyqueryparametersshouldbepassedasa parameters parameter,writtenbetween {} bracesas name : value pairs get requestparameterscanalsobepassedthisway,ifyoulike Prototype's Ajax Updater

new Ajax.Updater( " id ", " url ", { method: "get" } );

Ajax.Updater canbeusedifyouwanttofetchafileviaAjaxandinjectitstext/HTMLcontents intoanonscreen additional(1st)parameterspecifiesthe id oftheelementintowhichtoinjectthecontent

Ajax code bugs (10.2.5)

WhenwritingAjaxprograms,therearenewkindsofbugsthatarelikelytoappear.

Nothinghappens! The responseText or responseXML hasnoproperties. Thedataisn'twhatIexpect.

Howdowefindandfixsuchbugs? Debugging Ajax code

Net showseachrequest,itsparameters,response,anyerrors expandarequestwith +andlookat Response tabtoseeAjaxresult

XMLHttpRequest security restrictions

cannotberunfromawebpagestoredonyourharddrive canonlyberunonawebpagestoredonawebserver canonlyfetchfilesfromthesamesitethatthepageison www.foo.com/a/b/c.html canonlyfetchfrom www.foo.com 10.3: XML

10.1:AjaxConcepts 10.2:Using XMLHttpRequest 10.3: XML

What is XML?

XML :aspecificationforcreatinglanguagestostoredata;usedtosharedatabetweensystems abasicsyntaxoftags&attributes languageswritteninXMLspecifynames,attributenames,andrulesofuse Example:XHTMLisa"flavor"ofXML anadaptationofoldHTMLtofitXML'ssyntaxrequirements XMLspecifiestagsyntax: <...... ="..."> HTMLcontributestagnames(e.g. h1 , img )andattributes( id /class onallelements, src /alt on img tag) An example XML file

Tove Jani Reminder Don't forget me this weekend!

beginswithanheadertag,thenasingle document tag (inthiscase, note ) tag,attribute,andcommentsyntaxisidenticaltoXHTML's

What tags are legal in XML?

any tag you want ;thepersonstoringthedatacanmakeuptheirowntagstructure example:apersonstoringdataaboutemailmaywanttagsnamed to , from , subject example:apersonstoringdataaboutbooksmaywanttagsnamed book , title , author "GardenState "XML:ifyou'refeelingunoriginal,makeupsomeXMLnobody'severdonebefore quirkleblat Schemas

schema :anoptionalsetofrulesspecifyingwhichtagsandattributesarevalid,andhowtheycanbe usedtogether usedto validate XMLfilestomakesuretheyfollowtherulesofthat"flavor" XHTMLhasaschema;W3Cvalidatorusesittovalidate doctypeattopofXHTMLfilespecifiesschema twowaystodefineaschema: DocumentTypeDefinition(DTD) W3CXMLSchema (wewon'tcoverschemasanyfurtherhere)

Uses of XML

XMLdatacomesfrommanysourcesontheweb: web servers storedataasXMLfiles sometimesreturnqueryresultsasXML web services useXMLtocommunicate XMLlanguagesareusedfor music , math , vectorgraphics popularuse: RSS forfeeds&podcasts Pros and cons of XML

pro: easytoread(forhumansandcomputers) standardformatmakesautomationeasy don'thaveto"reinventthewheel"forstoringnewtypesofdata international,platformindependent,open/freestandard canrepresentalmostanygeneralkindofdata(record,list,tree) con: bulkysyntax/structuremakesfileslarge;candecreaseperformance example: quadraticformulainMathML canbehardto"shoehorn"dataintoanintuitiveXMLformat won'tneedtoknowhowforthisclass

Fetching XML using AJAX (template)

new Ajax.Request( " url ", { method: "get", onSuccess: functionName } ); ... function functionName (ajax) { do something with ajax.response XML ; }

ajax.response Text containstheXMLdatainplaintext ajax. response XML isapreparsedDOMobjectrepresentingtheXMLfileasatree(moreuseful) Using XML data in a

customflavorofXMLneedstobeconvertedtoXHTML,theninjectedintopage wewilltransformusingJavascriptXMLDOM basictechnique: 1. fetchXMLdatausingAjax 2. examinethe response XML object,usingDOMmethodsandproperties 3. extractdatafromXMLelementsandwraptheminHTMLelements 4. injectHTMLelementsintowebpage otherwaystotransformXML(notcovered):CSS, XSLT

Recall: Javascript XML (XHTML) DOM

AlloftheDOMpropertiesandmethodswealreadyknowcanbeusedonXMLnodes:

properties: firstChild , lastChild , childNodes , nextSibling , previousSibling , parentNode nodeName , nodeType , nodeValue , attributes methods: appendChild , insertBefore , removeChild , replaceChild getElementsByTagName , getAttribute , hasAttributes , hasChildNodes XML DOM tree structure

children computers ...

theXMLtagshaveatreestructure DOMnodeshaveparents,children,andsiblings

Analyzing a fetched XML file using DOM

WecanuseDOMpropertiesandmethodson ajax.responseXML :

// zeroth element of array of length 1 var foo = ajax.responseXML.getElementsByTagName("foo")[0];

// same var bar = foo.getElementsByTagName("bar")[0];

// array of length 2 var all_bazzes = foo.getElementsByTagName("baz");

// string "bleep" var bloop = foo.getAttribute("bloop"); Recall: Pitfalls of the DOM

WeareremindedofsomepitfallsoftheDOM:

// works - XML prolog is removed from document tree var foo = ajax.responseXML.firstChild;

// WRONG - just a text node with whitespace! var bar = foo.firstChild;

// works var first_baz = foo.getElementsByTagName("baz")[0];

// WRONG - just a text node with whitespace! var second_baz = first_baz.nextSibling;

// works - why? var xyzzy = second_baz.firstChild;

Larger XML file example

Everyday Italian Giada De Laurentiis 200530.00 XQuery Kick Start James McGovern 200349.99 Harry Potter J K. Rowling 200529.99 Learning XML Erik T. Ray 200339.95 Navigating the node tree

don'thave id sor class estousetogetspecificnodes firstChild /nextSibling propertiesareunreliable bestwaytowalkthetreeisusing getElementsByTagName :

node .getElementsByTagName(" tagName ")

getanarrayofall node 'schildrenthatareofthegiventag( "book" , "subject" ,etc.) canbecalledontheoverallXMLdocumentoronaspecificnode

node .getAttribute(" attributeName ")

getsanattributefromanode(e.g., category , lang )

Navigating node tree example

// make a paragraph for each book about computers var books = ajax.responseXML.getElementsByTagName("book"); for (var i = 0; i < books.length; i++) { var category = books[i].getAttribute("category"); if (category == "computers") { var title = books[i].getElementsByTagName("title")[0].firstChild.nodeValue; var author = books[i].getElementsByTagName("author")[0].firstChild.nodeValue;

// make an XHTML

tag based on the book's XML data var p = document.createElement("p"); p.innerHTML = title + ", by " + author; document.body.appendChild(p); } } A historical interlude: why XHTML?

inXML,different"flavors"canbecombinedinsingledocument theoreticalbenefitofincludingotherXMLdatainXHTML nobodydoesthis mostembeddeddataareinnonXMLformats(e.g.,Flash) nonXMLdatamustbeembeddedanotherway(we'lltalkaboutthislateron) requiresbrowser/pluginsupportforother"flavor"ofXML developmentslowtononexistent mostXMLflavorsarespecializeduses

Why XML in AJAX?

mostdatayouwantareprovidedinXML the de facto universalformat thebrowsercanalreadyparseXML(i.e.,XHTML)intoDOMobjects DOMonlydefinedforXMLbasedformats,maynotmapdirectlytoanotherformat wouldhavetomanuallyparseadifferentformat simpleformatscanbeparsedmanuallyfrom ajax.responseText mostdataareeasiertomanipulateasDOMobjectsthantoparsemanually Debugging responseXML in

canexaminetheentireXMLdocument,itsnode/treestructure