The Dojo JavaScript Toolkit Ajax Support

System Consultant

Topics in This Section

Overview of Dojo Installation and documentation Quick summary of dojo.query and selectors The dojo.xhrGet function and variants
Basics OptionsO ti Sending data Inserting HTML Handling JSON data


‡ Comparing Ajax support to other libraries
± Prototype, jQuery, Ext-JS

Overview of Dojo

‡ Core
Utilities for Ajax, CSS querying, DOM manipulation, cross-browser event handling, and general JavaScript programming

Very similar to jQuery

‡ Dijit
Large set of rich GUI components Much more extensive than jQuery UI

‡ DojoX
Charts, graphs, vector graphics, fancy widgets Similar to the jQuery Plugins


Core Utilities

dojo.query("css selector")
Returns a NodeList of matching DOM elements.
Almost identical to $("css selector") in jQuery.

Makes an Ajax GET request. Also dojo.xhrPost, etc.
Moderately similar to $.ajax({options}) in jQuery

dojo.xhrGet({ url: "address", load: responseHandler });

Calls function after DOM loaded.
Almost identical to $(function) jQuery

Loads Dojo libraries on the fly

Downloading and Installation
‡ Download
± ± Choose ³Download latest Stable Release´, then dojo release dojo release or dojo-release-x.y.z.tar.gz

‡ Installation
± Unzip release file, creating 3 subfolders: dojo, dijit, dojox

‡ Folders are quite large, but core file (dojo.js) is small. ‡ Other files are loaded on-the-fly based on dojo.require statements.

± Copy 3 folders to WebContent/scripts of Eclipse project ±

‡ Online documentation

6 or later (vs.0 for jQuery) ‡ Opera ‡ Chrome ± 1.Browser Compatibility ‡ Firefox ‡ Internet Explorer ± 6.1 or later (vs. 3.0 or later (same as jQuery) ‡ Safari ± 3.0 for jQuery) ± Dijit: 2.5 or later (vs 2.0 or later ± Core: 1. 9.0 for jQuery) ± Dijit: not supported! .0 or later (same as jQuery) ± Core: 9.

dojo.query & Selectors 11 Basics .

query("li b span.query("css selector") to get a set of DOM elements ‡ Then.blah") ‡ Return all <span class="blah"> elements that are inside b elements.blah") ‡ Return all elements that have class="blah" ‡ Return all p elements ± dojo. perform operations on each (see next page) ‡ Examples ± dojo.Selecting DOM Elements ‡ Idea ± Use dojo.query("#some-id") ‡ Return 1-element set (or empty set) of element with id ‡ Simplest use and most common for Ajax (note the ³#´!) ‡ Can also use dojo.query("p") ± dojo. that in turn are inside li elements .query(".byId("some-id") to get single element 13 ± dojo.

forEach(f2) .play() ‡ Makes invisible. etc.require("dojo. ± dojo.value ‡ Returns value of input element.query("selector").onclick(function) ‡ Adds onclick handler. etc. ± dojo.Manipulating DOM Elements ‡ Common functions on matched elements ± dojo.query("selector"). 14 ± dojo.addClass("name") ‡ Adds CSS class name to each. Also wipeIn. ³this´ set to element. ± dojo. fadeIn. ± Must use dojo. Notice no ³#´. fadeOut.NodeList-html").html("<tag>some html</tag>") ‡ Sets the innerHTML of each element.#.wipeOut().query("a").onclick(f1).query("selector").addClass("name").query("selector"). Also removeClass toggleClass ± dojo. onmouseover. Also onchange. ‡ Chaining ± dojo.query("selector").byId("some-id").forEach(function) ‡ Calls function on each element.

Explained in next section.onclick(randomizeHeadings).onclick(revertHeadings).NodeList-html.require("dojo.Example: Randomizing Background Colors (JavaScript) dojo. Sets onclick handlers 16 .NodeList-fx").require´ statement.query("#button1"). }).ti Loads extra JavaScript on the fly. The online docs tell you if a certain function necessitates a ³dojo require´ statement³dojo. dojo.query("#button2"). Like smart window.addOnLoad(function() { dojo.NodeList-fx and dojo. 15 The main two needed for basics apps are dojo.onload. dojo.

addClass(randomStyle()). Slowly hide every h3 that has CSS style ³green´.play().green").query("h3"). function setRandomStyle(heading) { dojo. dojo.query(heading).wipeOut(). ³yellow´ or ³green´ CSS names to each .query("h3.Example: Randomizing Colors (JavaScript Continued) function randomizeHeadings() { dojo. which you then call play on.forEach(setRandomStyle). } Add ³red´. } Note difference from jQuery approach: wipeOut returns an Animation.

} function randomElement(array) { var index = { background-color: green } 18 .removeClass("green").yellow { background-color: yellow } . } 17 function revertHeadings() { dojo. "green"].floor("red") .green"). return(array[index]).random()*array.query("h3"). return(randomElement(styles)).query("h3. } Example: Randomizing Colors (Style Sheet) .length). "yellow".Example: Randomizing Colors (JavaScript Continued) function randomStyle() { var styles = ["red". dojo.removeClass("yellow") .wipeIn().red { background-color: red } .

Example: Randomizing Colors (HTML) « <head><title>Dojo Basics</title> <link rel="stylesheet" href="./scripts/dojo/dojo.css" type="text/css"/> <script src=".js" type="text/javascript"></script> <script src="./scripts/dojo-basics./css/styles.js" type="text/javascript"></script> </head> 20 .

blah. yadda. blah. blah</h3> <h3>Yadda.Example: Randomizing Colors (HTML Continued) « <h3>Foo. yadda</h3> <h3>Foo. yadda. then gradually disappeared. or after ³Revert Headings´ . 21 Example: Randomizing Colors (Results) After ³Randomize Headings´. b<h3>Fbar. yadda.<h3>Foo bar baz</h3> <h3>Blah. blah.<h3>Foo bar baz</h3> <h3>Blah. yadda</h3> <form action="#"># <input type="button" id="button1" value="Randomize Headings"/> <input type="button" id="button2" value="Revert Headings"/> </form> « The ids to which onclick handlers were attached. Some headings turned green. bar. b </h3>baz</h3> <h3>Blah. 22 When page originally loaded. blah</h3> <h3>Yadda. bar. yadda</h3> <h3>Foo. blah</h3> <h3>Yadda.

} .query("h3"). } 23 ‡ Why can¶t I simply do this? function randomizeHeadings() { dojo.addClass(randomStyle()). } function setRandomStyle(heading) {").query("h3. dojo. dojo.wipeOut().forEach(setRandomStyle).play().green").play().Understanding Operations on Sets of Elements ‡ Instead of this function randomizeHeadings() { dojo.query("h3").query(heading).addClass(randomStyle()).wipeOut().query("h3.

xhrGet: Basic Syntax ‡ dojo.xhrGet({«}) ‡ url. handleAs 26 . ‡Options for dojo. load: funct}).xhrPut. error.xhrGet({url: "address". dojo. 25 ± Handler function gets response text. Response text is considered a string unless you use handleAs option. load ± Almost-always used ± Other common options ‡ content.xhrPost. preventCache. etc. dojo. ‡ Also dojo.xhrDelete.dojo.xhrGet(optionsObject) ± Minimal form: dojo.

request.ActiveXObject) { return(new ActiveXObject("Microsoft.Data-Centric Ajax with and without Toolkits ‡ With basic JavaScript function getRequestObject() { if ("GET". "some-url". } } function sendRequest() { var request = getRequestObject(). } else { return(null). } . request. } else if (window. }.XMLHttpRequest) { return(new XMLHttpRequest()). true).XMLHTTP")). request.onreadystatechange = function() { someFunct(request).send(null).

request({url: "address". ‡ Dojo (handler passed response text) dojo.Ajax. .xhrGet({url: "address". {onSuccess: handlerFunct})." load: handlerFunct}). ‡ Prototype (handler passed response object) 27 new Ajax.Request("address". success: handlerFunct}).Data-Centric Ajax with and without Toolkits ‡ jQuery (handler passed response text) $. success: handlerFunct}).ajax({url: "address". ‡ Ext (handler passed response object) Ext.

y of showAlert for the success parameter. but you can declare a second argument (ioArgs) if you want the response object (XmlHttpRequest) and other information. This way.xhrGet Example Code: JavaScript function showTime1() { dojo. load: showAlert. } The preventCache option is not required. } This is the response text.xhrGet({ url: "show-time. preventCache: true }). so you cannot use alert instead. function showAlert(text) { alert(text). Also note that the latest Firefox does not let you pass native functions here. but is a convenient option when the same URL (including query data) yields different responses. you don¶t have to send Cache-Control and Pragma headers from server.dojo. 28 .jsp".

.Date() %> 30 .js" type="text/javascript"></script> <script src=".. <script src=".xhrGet Example Code: JSP It is now <%= new java.dojo.xhrGet: Basics (Using explicit onclick handler in HTML)</legend>) / <form action="#"> <input type="button" value="Show Time" onclick="showTime1()"/> </form> </fieldset>« 29 dojo.util.js"src=" /scripts/dojo ajax js" type="text/javascript"></script> </head> <body>..xhrGet Example Code: HTML « <head><title>Dojo and Ajax</title>Ajax</title>./scripts/dojo/dojo./scripts/dojo-ajax.. <fieldset> <legend>dojo.

dojo.xhrGet : Results .

Dojo (and jQuery) advocate setting it in the JavaScript instead ‡ Often referred to as ³unobtrusive JavaScript´: no explicit JavaScript anywhere in the HTML page ‡ Function runs after the DOM is loaded. for images.addOnLoad(function() {«}).Registering Event Handlers in JavaScript ‡ Basic approach ± Previous example set the onclick handler in the HTML. Handler is passed a DOMEvent with characteristics that are unified across browsers ‡ Dojo support ± dojo. ‡ Assigns onclick handler.onload ‡ Use this approach to set up all event handlers ± dojo. but does not wait. Although this is common with other Ajax libraries. .onclick(someHandler). as with window.query("#some-id").

} 34 .onclick(showTime1).query("#time-button-1"). } These two functions are unchanged from previous example.Redoing Time Alert: JavaScript dojo.jsp". preventCache: true }).xhrGet({ url: "show-time. 33 function showTime1() { dojo.addOnLoad(function() { dojo. function showAlert(text) { alert(text). load: showAlert. }).

Redoing Time Alert: HTML <fieldset> <legend>dojo.xhrGet: Basics (Registering in JavaScript)</legend> <form action="#"> <input type="button" value="Show Time" id="time-button-1"/> </form></f> </fieldset> onclick handler .

35 dojo.Redoing Time Alert: Results Works exactly the same as previous exampleexample.xhrGet Sending Data .

Ajax Functions ‡ dojo. hasBody) ± Lets you send arbitrary HTTP commands ‡ dojo.rawXhrPost.rawXhrPut ± Sends a POST or PUT request.xhrDelete ± Make a PUT or DELETE request ± Unsupported on many servers ‡ dojo. dojo.xhrGet({options}) ± Make a GET request ‡ dojo.xhrPut. but lets you provide the raw data for the body of the request 38 . {options}.xhrPost({options}) 37 ± Makes a POST request ‡ dojo.xhr("method". dojo.

xhrGet. content: «}).xhrGet({ url: «. in POST body for dojo. load: «. param2: "baz"}}).xhrPost ‡ See later example for building the string automatically using the ³form´ option ‡ Works identically to ³parameters´ option in Prototype or ³data´ option in jQuery ‡ Examples ± dojo. .xhrGet({« content: { param1: "foo bar!³.Overview ‡ dojo. ± Content value is an object: query string gets built out of property names and URL-encoded property values ‡ On end of URL for ajax.

39 function showAlert(text) { alert(text). } Same function used in earlier examples. content: { param1: "foo".jsp". } The preventCache option is not used since the same data always results in the same response. function showParams1() { dojo. param2: "bar" }. « }).addOnLoad(function() { dojo.query("#params-button-1").xhrGet({ url: "show-params. load: showAlert }).Content Example: JavaScript dojo. 40 .onclick(showParams1).

xhrGet: The 'content' Option</legend> <form action="#"> <input type="button" value="Show Params" id="params-button-1"/> </form> </fieldset> « .Content Example: HTML « <fieldset> <legend>dojo.

param1 is ${param.param1}. param2 is ${param param2} 41 Content Example: Results 42 .

Content Example: JSP .

handleAs: "json" }). param2: "baz"}. content: { param1: "foo bar".xhrGet({ url: "address". load ± dojo. error: errorHandlerFunction.xhrPost and others ‡ Common options: example dojo.Overview ‡ Options (almost) always used: url. . ‡ load is not strictly required.xhrGet({url: "some-address". load: successHandlerFunction.. preventCache: true. you might want to just fire off some data to the server and not display any thing ‡ Options apply equally to dojo. load: someFunc}).

Function gets passed 2 args: the data returned from the server (formatted according to the handleAs property). json.Mtot l d dti None handleAs The format in which to pass the response to the handler function. The ioArgs object has many properties. None form Id of a form whose fields will be serialized to form the query data. url. The object property names become request param names and property values get URLencoded and become request param values. jsoncomment-filtered. Sent in the appropriate place depending ontti ll S t i thi t lddi whether it is GET or POST. json-comment-optional. More common t use separate load and error properties. & and = inserted automatically. EmptyE t error 45 Function to be called if request fails due to server error. but most useful are args. "text" 46 . and javascript. query. expired timeout. None handle Function to be called whether or not request was successful. or exception thrown from main response handler. Legal values are text. xml. and an ioArgs object.Options Name Description Default content Data tD t to send t server. in the form on an object with param namesd toi th fbj t ith and raw (non-escaped) param values. and xhr.

Infinity None The address to req est Sho ld be a relati e URLrequest. and an ioArgs object.gjgj has many properties.Options (Continued) headers ExtraE t HTTP request headers to be sent to the server. and xhr. the error handler will be called instead of the load handler. query. true. false Default url Timeout in milliseconds. but most useful are args. If request takes longer.preventCache parameter with a timestamp that changes with each request. Shouldrelative URL. url. false timeout Name Should the request be synchronous? Use synchronous requests Description with caution since they lock up the browser. Function gets passed 2 args: the data returned from the server (formatted according to the handleAs property). The ioArgs objectp p y). dojo. .th d t bt t th NoneN load Function to be called if request succeeds. None preventCache Is browser prohibited from caching the page? Set to true if you sync use GET and you could get different responses back from the same data If true then the URL is appended with adata.

} ‡ Prototype function ajaxResult(address.get(resultRegion).Inserting Results into HTML: The ³html´ Function Content-Centric Ajax with and without Toolkits ‡ jQuery function ajaxResult(address. ‡ Ext-JS function ajaxResult(address. } ‡ Dojo ± N explicit support for content-centric Ajax.load(address). resultRegion) { Ext.load({ url: address}).Updater(resultRegion. resultRegion) { $(resultRegion). resultRegion) { new Ajax. } 48 . Response handler uses ³html´ to do the insert. address).

Supply values to ³content´ property ± No need to escape values first ‡ dojo.e.value }).value ± Note that there is no # before the ID. 2. nothing equivalent to jQuery¶s $("#some-id"). since you are not doing a CSS match.xhrGet({« content: { param1: dojo. Use dojo.Reading Textfield Values 1..val(). I. but rather using a shortcut for document.byId("id1").getElementById ± Also note that Dojo has no way of looking up values directly from a NodeList resulting from a Dojo query.byId("some-id"). ‡ Shortcut ± See upcoming section on ³form´ property 49 50 .

query("#params-button-2") .onclick(showParams2).addOnLoad(function() { dojo.require("dojo.Ajax with HTML Insertion: JavaScript (Setup) dojo. dojo. . « }).NodeList-html").

"#result1"). selector) { dojo.jsp".query(selector).byId("field1"). } function insertText(text.value. } }). load: function(text) { insertText(text. } 51 52 .Ajax with HTML Insertion: JavaScript (Main Code) function showParams2() { dojo.html(text). param2: dojo byId("field2") value}. content: { param1: dojo.xhrGet({ url: "show-params.

xhrGet: HTML Insertion</legend> <form action="#"> param1: <input type="text" id="field1"/> <br/> param2: <input type="text" id="field2"/> <br/> <input type="button" value="Show Params" id="params-button-2"/> <h2 id="result1"></h2> </form>/ </fieldset> « .HTML Insertion: HTML Page « <fieldset> <legend>dojo.

param2 is ${param param2}.param1}.HTML Insertion: JSP param1 is ${param. 53 HTML Insertion: Results 54 .

resultRegion) dojo. address).require)) function ajaxResult(address. resultRegion) { $(resultRegion).html(text). } ‡ Dojo (also need dojo. } }). resultRegion).Updater(resultRegion. resultRegion) { new Ajax. } . load: function(text) { insertText(text.query(selector). } function insertText(text.HTML Insertion: Comparing Prototype.xhrGet({ url: address. jQuery and Dojo ‡ Prototype function ajaxResult(address. selector) { dojo.load(address). } ‡ jQuery 55 function ajaxResult(address.

‡ Note: no # before the id ‡ Advantages ± One simple option. unchecked radio buttons or checkboxes are ignored) ± Giving names to input elements is familiar to HTML developers .Building Parameter Strings Automatically with ³form´ Using ³form´ Option ‡ Idea ± You specify a form. and Dojo automatically builds query string from all appropriate input elements.g. form: "some-id" }). ± The element names (not ids) become the param names ‡ Syntax ± dojo. no matter how many input elements ± Only takes values of active elements (e..xhrGet({ url: «. load: «.

onclick(showParams3). dojo. form: "form1". } « 58 . 57}).³form´ Example: JavaScript dojo.NodeList-html").´#result2").require("dojo. } }).jsp".query("#params-button-3") . function showParams3() { dojo.addOnLoad(function() { dojo.xhrGet({ url: "show-params. load: function(text) { insertText(text.

xhrGet: Simplifying Params with 'form'</legend> <form action="#" id="form1"> param1: <input type="text" name="param1"/> <br/> param2: <input type="text" name="param2"/> <br/> <input type="button" value="Show Params" id="params-button-3"/> <h2 id="result2"></h2> </form> </fieldset> « 59 ³form´ Example: JSP param1 is ${param.param1}. param2 is ${param param2}.³form´ Example: HTML « <fieldset> <legend>dojo. 60 .

³form´ Example: Results 61 Handling JSON Data .

: ‡ dojo.g.xhrGet({url: address. E.cto + "</b>"). E.Approach ‡ Server ± Returns JSON object with no extra parens. No need for parsing or ³eval´. Must build HTML from result. load: handler.:i³ l´ M b ildfl E ‡ function handler(companyExecutives) { dojo.html("<b>Chief Technology Officer is " + companyExecutives. E.: ‡ { cto: "Resig ".query("#some-id") . } 64 . ceo: "Gates ".xhrGet 63 ± Specifies ³json´ for handleAs.g. coo: "Ellison" } ‡ Code that calls dojo xhrGetdojo. handleAs: "json"}).j({j}) ‡ Response handler ± Receives JavaScript data as first argument.g.

bg.require("dojo.jsonData fontSize jsonData. jsonData. jsonData.dojo addOnLoad( ).JSON Example Code: Core JavaScript dojo. function showNums() { j({dojo. } function showNumberList(jsonData) { var list = makeList(jsonData. handleAs: "json". load: showNumberList.addOnLoad(«).numbers).fg.NodeList-html"). int dojo. preventCache: true }).xhrGet({ url: "show-nums".fontSize. Array of doubles } .query("#result3").html(list). dojo.

f tSi ) {fontSize) return( "<div style='color:" + fg + ". " + "background-color:" + bg + ". fontSize. b(fbg. } function li tSt tTftilistStartTags(fg.JSON Example Code: Auxiliary JavaScript 65 function makeList(fg. bg. " + "font-size:" + fontSize + "px'>\n" + "<ul>\n"). } 66 . nums) { return( listStartTags(fg. fontSize) + listItems(nums) + listEndTags()). bg.

i<items. } function listEndTags() { return("</ul></div>"). } .JSON Example Code: Auxiliary JavaScript (Continued) function listItems(items) { var result = "". for(var i=0. } return(result). i++) { result = result + "<li>" + items[i] + "</li>\n"..length.

xhrGet: Treating Response 67 as JSON</legend> <form action="#"> <input type="button" value="Show Nums" id nums button />id="nums-button"/> <div id="result3"></div> </form> </fieldset></fi ld t> « 68 .JSON Example Code: HTML « <fieldset><fi ld t> <legend>dojo.

setHeader("Cache-Control".jsp".include(request. }} .random().setAttribute("nums". request. Math. nums). request.randomColor(). double[] nums = { Math random() Math random() Math random() }. "no-cache").randomInt(30)).request.setAttribute("fg". fontSize).setHeader("Pragma". IOException { response.randomColor().JSON Example Code: Servlet public class ShowNumbers extends HttpServlet { public void doGet(HttpServletRequest request. bg). String bg = ColorUtils.setAttribute( bg .p(g.) String fg = ColorUtils.Math. response). "no-cache"). dispatcher.random().setAttribute("bg".getRequestDispatcher(outputPage). request.random() request. response. response. fg).setAttribute("fontSize". String outputPage = "/WEB-INF/results/show-nums. String fontSize = "" + (10 + ColorUtils. Math. HttpServletResponse response) throws ServletException.setContentType("application/json"). RequestDispatcher dispatcher = request.

bg: "${b }"b"${bg}". ${nums[2]}]{[ ]}. numbers: [ ${nums[0]}. {[ ]}. Dojo will wrap in parens and then pass to ³eval´ (or equivalent functionality)eval ± Types ‡ fg and bg: Strings ‡ f tSifontSize: i tint ‡ numbers: Array of doubles . fontSize: ${fontSize}. ${nums[1]}. {[ ]}] } 69 ± No enclosing parens.JSON Example Code: JSP ‡ Notes { fg: "${fg}".

"yellow" }. "olive". */ public static int randomInt(int range) { return(new Random(). "silver". at random. */ public static String randomColor() { return(colors[randomInt(colors. "green". "maroon".( l[d( llh)]) } 70 } . /** A random number between 0 and range-1. } /** One of the official HTML color names.length)]). inclusive. "black". "lime". "teal". "navy".nextInt(range)). "gray". "fuchsia". "white". "red".JSON Example Code: Auxiliary Java Code public class ColorUtils { pprivate static String[] colors = {g[] "aqua". "blue". "purple".

JSON Example: Results 71 Wrap-up .

org/docs ± Moderately complete ± Moderately well organized ± Large number of explicit examples 74 . ‡ Usage in industry ‡ Looking ahead ‡ Rich GUIs ‡ Familiarity to JS developers 73 ± Leaders: Ext-JS. YUI. JSON-RPC ± Leader: jQuery ± 2nd tier: Ext-JS. Dojo. Dojo ± 2nd tier: jQuery UI GWTUI. OrchardM ‡ Concise Guide to Dojo ‡ http://dojotoolkit.³Best´ JavaScript Librariesp ‡ General JS programming ± Leader: Prototype ± Leader (only): GWT ‡ Traditional Ajax support ± Tie ± Leader: GWT ± 2nd tier: DWR. jQuery released CSS matching library separately (http://sizzlejs. YUI. ± Lowest: GWT Books and References ‡ Dojo: The Definitive Guide ± by Matthew A. Russell ‡ Mastering Dojo ± b C i Ri k et alby Craig Rieckel ± by Leslie M. GWT ± All these entries are likely to c ge s g cchange significantlyy ± Lurking on the horizon: Google ³Closure´ library ‡ Other programming (Java) ‡ Server communication ‡ DOM manipulation ± Leader: jQuery ‡ Oth copying jQuery approach andOthersi jQh d closing gap. Prototype.

load: handlerFunction.onclick(someFunction). ‡ Inserting HTML (content-centric Ajax) dojo.NodeList-html"). function h dl FftihandlerFunction(text) {ti (t t) dojo. ‡ General Ajax requests (data-centric Ajax) 75 dojo. handleAs: "json" }).xhrGet({ « (omit handleAs) « }). . } .query("#some-id").addOnLoad(function() { dojo.Summary ‡ Assigning event handlers programmatically dojo.query("#some-id"). form: "form-id. }).html(text).xhrGet({ url: "relative-address".require("dojo. dojo.

Sign up to vote on this title
UsefulNot useful