Login Register

Passing Data with JSON

JSON, or Javascript Object Notation, is a lightweight data interchange standard.   It can, in theory, be used to pass data between any two programming languages, but it has special advantages when used with Javascript.  JSON is fundementally just the Javascript array and object initializer syntax on its own.  So this array of objects in a Javascript program:

var cobblers = [
   {"filling": "peach", "timeToBake": 30 },
   {"filling": "cherry", "timeToBake": 35 },
   {"filling": "blueberry", "timeToBake": 30}
];

Roughly everything after the "=" is JSON.  Here's what the JSON packet would look like coming back from a web service:

{ "cobblers": [
       {"filling": "peach", "timeToBake": 30 },
       {"filling": "cherry", "timeToBake": 35 },
       {"filling": "blueberry", "timeToBake": 30}
    ]
}

"Excuse me," you might say, "but we already have a data interchange format.  You might have heard of it ... it's called XML."   So why not just pass it as:

<cobblers>
   <cobbler filling="peach" timeToBake="30" />
</cobblers>

The answer is performance, performance, performance!  JSON data is parsed up to 100 times faster than XML.  That makes sense because the parser is just eval().  For small portions of data, this doesn't mean much, but for large ones it's indispensible.  XML expressed in Javascript must carry the full weight of XML - including namespaces, DTD's and schemas.  Furthermore, the DOM representation of XML is much more memory-intensive than native Javascript.

Add to that the fact that XML is interpreted a little differently in each browser, and JSON is the preferred method for data interchange in dojo.  XML is supported, but you might not want to use it in simple scenarios. Where it really begins to make sense, however, is when large scale transformations are needed on the client side. Almost every modern browser today provides a client-side XSLT transform facility which can often outstrip JSON for speed in transforming large data sets from one structure to another since that transformation is handled in C or C++ and not in JavaScript. Whether your app chooses to use JSON or XML is often a foregone conclusion, but be aware that there are tradeoffs for each.

Accepting JSON Data in dojo.xhrGet

Provided your web service sends JSON (as the above example shows) Dojo pretty much handles the rest for you, including parsing the JSON into a JavaScript object. All you have to do is specify a JSON content handler:

dojo.xhrGet( {
        // The following URL must match that used to test the server.
        url: "http://server/ajax.txt",
        handleAs: "json",
        load: function(responseObject, ioArgs) {
          // Now you can just use the object
          console.dir(responseObject)// Dump it to the console
          console.dir(responseObject.cobblers[0].filling)// Prints "peach"
          return responseObject;
        }
        // More properties for xhrGet...
});

How about a "send" example

It would be useful to have an example of posting a JavaScript object back to a server using XHR to send it serialized as JSON. Why do you think it is not useful to send data to the server in this way? Seems like using JSON as a means of synchronizing an object on the server and a JavaScript object on the client would be both natural and useful. If I send down a list of objects in JSON and add a new one on the client, I would like to easily post back the new object as JSON.

to and from JSON

I'm new to Dojo, but not to programming (30 years) I've done it all, but the new technology looks like it will allow me to realize a project I've had on the go for over 20 years, but could not make it work properly because of technical limitations. I've got the server side covered, and the design, what I haven't found is a really easy way to integrate Front end and Back end. I'm convinced that JSON is the syntax, but haven't found a really easy way to loosely bind the front end to the back end.

I'm looking at other frameworks, like prototype etc. but to make it really easy to use, I need, basically, a front end that will take it's data and controls in JSON from an Ajax request, and return JSON and controls to the server. Not too much to ask, surely. Can anybody help?

PS it should also be it easy to select behaviours with and IDE like Zend, eclipse or dreamweaver.

A way to send JSON serialized data to the server

Hi,

I was also trying to send the JSON object to the server, and I solved it doing this:

// data = json-structure
var data = {'test':'foo','test2':{sub1:'bar'}};

dojo.rawXhrPost( {
        url: "url.php",
        handleAs: "json-comment-filtered",
        postData: dojo.toJson(data),
        timeout: 1000,
        load: function(response, ioArgs) {
                return response;
        },
        error: function(response, ioArgs) {
                return response;
        }
});

On the server-side (in url.php), I can now do:

$input = json_decode(file_get_contents('php://input'));

this gives me the json-structure as a php-array.

maybe this can be usefull, because I haven't found any examples of anything like this.

Syntax Error

Hi,

I am getting a syntax error with the above code

responseObject.cobblers has no properties

any ideas?

Adrian

What does firebug say?

Are you seeing a 404 or other type of error in Firebug?

--
Project Lead, The Dojo Toolkit
President, The Dojo Foundation

input for datastore?

How can I parse json-data from XhrGet into a datastore?

Thanks for help!

Does Dojo support geting value in XMLDocument object?

Hi All,
I'm just a new born with Dojo. Could you please let me know if Dojo supports us to get a value of an element in XMLDocument, or we have to do it manually?

Thanks for help!

How to populate a html option list based on json

I wonder if there is any existing library in dojo to populate an array or list of json objects that are returned from server through xhr call.
I can manually do it with javascript looping to construct option list. But is there any ready to use function to do that?
The same question for widget too.
Is there any example code?

Thanks.

404 error in firebug

Hi All I am trying to run the below code in my javascript file,  I have  JavaToJson mapper code so I am not parsing it off hand. But I am not able to fetch this string in my request processor, it reaches there as a null. If anybody has an idea please let me know.

 Just to add I am porting my code from 0.43 to 0.9 so the whole REST/JSON thing was working fine earlier and I would receive a proper string in using 0.43.

var username = dojo.byId("j_username").value;
var password = dojo.byId("j_password").value;
var jsonstr = "{ \"username\" : \""+ username +"\", \"password\" : \""+ password +"\"}";
alert("json string " + jsonstr);
dojo.xhrPost(
{
url: '/LAMConsole/rest/login',
sync: false,
handleAs: 'json',
content: jsonstr,
load: function(data, event)
{
loginSucess(data);
},
error: function(data,event)
{
displayError(data,event);
},
mimetype: 'application/json-comment-filtered'
});