Meta

Archives

Pages

Dojo, Ajax and JSON

In the book “Learning Dojo” by Peter Svensson Ajax is covered in chapter 4 “Dojo Ajax Feature” and a common way to send an asynchronous request to a server is this one:

1:var x;

2: dojo.xhr("Get",

3: {

4: url:"/yourserver/server.php",

5: handleAs: "text",

6: load: function(data, ioArgs)

7: {

8: x = data;

9: }

10: });

11: console.log("x == "+x);

Details about the XMLHTTP request object ( abbreviated XHR ) can be found here. Besides “Get” of course “Post”, “Put” and “Delete” can be used as well. The difference between “Get” and “Post” is, as far as I understood from this book, that “Post” sends parameter to the server in a more hidden way, as part of the document sent to the server, while with “Get” parameters are added to the URL, thus become visible and of course easier to hack.

Anyway, my focus in this blog posting is on the “handleAs” attribute of the dojo.xhr call. The terms “XMLHTTP” or “Ajax” suggest – since the “x” in “Ajax” stands for XML as well – that data is exchanged between client and server in XML format. Which is one possible way to do it, but not the only one. The example above shows a second way: exchanging simple (unformatted) text.

A third option is using JSON ( and there are some variants like ”json-comment-optional” or “json-comment-filtered”, see here ) and I have read comments from many people saying that parsing JSON data is faster than parsing XML. Since JSON stands for JavaScript Object Notation it is easy to imagine that this might be the right thing to do when using Javascript.

I spent an hour or so to figure out how this works, since even it has been mentioned in this book I couldn’t find any example. Key is to specify

1: handleAs: “json”

as a parameter to the dojo.xhr call. So much to do on the client side, except later on dealing with the returned Javascript objects. Interesting is to find out what to do on the server side, when using php for instance.

What I did in my trial was to setup an array in php to be returned to the client. Thus, part of the server code looks like this, and key to success was to use the json_encode function on the array returned: