This week’s installment of Dojo Goodness demonstrates dojo.xhrGet, an easy way to sprinkle some AJAX into your application and one of the biggest staples in Dojo. (In case the “xhr” part of that API call is a curve ball, it simply refers to the XMLHttpRequest object.) The xhrGet function streamlines the work entailed in issuing a GET request to the server, is included in Base, and is intuitive to use in that you pass it some descriptive keyword arguments; the default behavior is to issue an asynchronous request.
Here’s the basic boilerplate:
dojo.xhrGet({
url : "localresource.json",
handleAs : "json",
load : function(response, ioArgs) {
/* Handle a successful callback here */
return response;
},
error : function(response, ioArgs) {
/* Handle any errors that occur here */
return response;
}
});
Assuming you have a resource on your server called localresource.json that returns back some JSON, you can access it via the load function’s response parameter just like any other JavaScript object since handleAs was configured accordingly. If an error were to occur either in the call to the server or in the load function itself, the error handler kicks in to give you a place to take care of the mess. The ioArgs parameter can be used to inspect info such as the original request that was sent to the server.
Let’s go ahead and kick the tires a bit. First, store the following file somewhere locally:
<html>
<head>
<title>Easy AJAX!</title>
<script
type="text/javascript"
src="http://o.aolcdn.com/dojo/1.0/dojo/dojo.xd.js"
djConfig="isDebug:true"
></script>
<script type="text/javascript">
dojo.addOnLoad(function() {
dojo.xhrGet({
url : "localresource.json",
handleAs : "json",
load : function(response, ioArgs) {
// inspect the response and ioArgs...
console.log(response, ioArgs);
//do some stuff with the response...
console.log(response.foo);
console.log(response.bar);
console.log(response.baz);
//uncomment to cause an error and see the error handler kick in.
//console.log(response.foo.bar.baz);
},
error : function(response, ioArgs) {
console.log("An error occurrerd.", response, ioArgs);
}
});
});
</script>
</head>
<body>
Nothing to see here. Check the console...
</body>
</html>
Next, store the following simple structure in a file called localresource.json, and place it alongside the HTML file:
{
'foo' : 1,
'bar' : 2,
'baz' : 3
}
When you load up the HTML file, you should see some activity in Firebug related to the GET request and the console.log functions where we treat the response parameter as an ordinary JavaScript object.
All in all, that’s the basic story for injecting some AJAX into an existing app. Hopefully, you agree that it should have been that easy.
Of course, GET requests aren’t all you can do. Referencing Dojo’s official API, there’s also a variety of other XHR functions including xhrPut, xhrPost, rawXhrPut, rawXhrPost, and as of version 1.1, a general-purpose xhr function that allows you to pass in the request type, which might be useful for HEAD requests among other things.
For complete coverage of the entire I/O subsystem in Dojo, be sure to check out my upcoming book. There’s an entire chapter devoted to virtually every topic related to server side communication, which includes IFRAME transports, JSONP, JSON-RPC, and more.
As always, leave feedback below if there is a topic that you’d like to see in an upcoming column. It can be something as simple as what we talked about today or something as complex as using an ill-documented DojoX subproject. (In other words, you might just be able to get some free consulting out of this column if you are sneaky enough…)


Matthew,
Great series! I do have a question that upon Googling it is clear there is no clear decision. My question goes to the "Like to see in an upcoming column." I am writing an application with GWT and was turned onto Dojo because it apparently is developed with 508 compatibility in mind. What are your thoughts on GWT vs Dojo, and more in general, what design practices (graceful degradation for example -- although I would argue that GD isn't really about degrading an application but rather providing an entirely separate one) one uses to develop 508 accessible code with Dojo (or GWT for that matter if you happen to know)?
wenxian
Hi, I ordered your book. I am very impressed with the Dojo kit,
using it to program my system's end-user frondend. Then plan to use the upcoming dojo 1.2 to program the configuration editor using AdobeAir and Dojo.
I have had quite a bit of difficulties finding out how JSONP
works (since I need to load cross-domain data).
I had to look through the source code of the
dojo/rpc/JsonpService
and the only function I could use there to make a call
was bind. And with that function apparently underneath
the GET method is used, and I still do not know how to use
the POST method for JSonp.
Another thing, I could not find a good explanation
how the 'deferred' argument is to be used
when calling dojo.rpc.JsonpService
Because for JsonP one already has to specify the callback
function as a parameter:
var srvc=new
dojo.rpc.JsonpService(
{url:"this one does not matter",
callbackParamName:"my_callback",
timeout: "3000"
}
);
And then the deferred argument that is passed
to the bind call does not appear to be used....
This area is confusing (I read that
the upcoming version 1.2 will have more cross-domain
communications support, but this will be some time
before 1.2 gets out there on the CDN sites, and your book
will probably not talk about it (since it is still work
in progress).
Another area of difficulty is figuring out how to use
DOJO's base APIs to 'improve' the robustness of my own
java script
code -- using dojo's Function binding, Modularization and
other facilities and conventions.
In other words, Dojo kit is well written but it would be
nice to understand design patterns, conventions/etc that
were used to achieve such a high-level of robustness and
complexity.
In order to use the same methods for our own development
@vlad_dojo: Hey - I do cover jsonp somewhat extensively in the book as do I provide extensively coverage of Deferreds and how they are used and propagated in the I/O subsystem, and virtually all of Base and Core.
I can totally empathize with you on having to grok source code. It's not fun and far from ideal -- in fact, that's a huge reason why I wrote the book. I really do think my book will help you in these areas. I tried really hard to elaborate on patterns and generalities across the broader parts of the toolkit without sacrificing details on the nitty gritty.
Could you do me a favor and post something back once you receive the book and have a chance to determine how well it did/didn't meet your needs?