Blogsite that talks about web Programming experiences,techniques and ideas for ASP,PHP,ASP.NET and Javascript.

Help get peace of mind knowing that everything is managed for you with Windows Live OneCare—virus and spyware scanning, firewalls, tune-ups, file backups, the whole nine yards. And it's all delivered to you in a smooth, hassle-free package. Download the 90 day free trial

So you have decided to use JSON over XML?

April 3rd, 2008 by Roy L. `dshiznitz Besiera

A few years ago i was very excited about this new technique to get content from another page without refreshing the browser. It is called AJAX. With AJAX (Asynchronous Javascript and XML), you can present data to your audience without interfering the behavior of the current page. It was the feeling that i discovered something new and i was very excited to use it on my website. So i started dipping my finger into the pool, it was cold (i hate it when it is cold) but still i managed to get my whole body wet and no later i found out i was already swimming.

I wouldn’t go into the technical details very much about AJAX, all i can say is that it uses the XMLHttpRequest object which is native among modern browsers and i believe it is an active X object in IE browsers (IE 6 i reckon). This object can be use to issue asynchronous request (request is made independent of the main page) on the server in the background. So you issue a request, the server responds, you process the response and finally present this data to your user. This is all done without refreshing the browser, means the state of the current page is maintained except for some elements involve in the request. In fact i actually created an AJAX Shoutbox AJAX shoutboxout of this idea written in ASP back in the “simple days” i wouldn’t say old, simple is the term i want to use ^^.

its pretty straighforward and though the term AJAX sounds exclusively using the XML format (hence Asynchronous Javascript and XML) as a response, you’ll be surprised it is not limited to that format. You can also use the property of the requesting object (XMLHttpRequest) responseText to tell the object that you are expecting a RAW text as a response type. Of course in your page that process this request it should return a raw text also and not an XML format same as you’re expecting an XML format using responseXML. I am really glad i took time learning and experimenting this technique using pure javascript 2 years ago before i decided to use javascript frameworks abstracting away the basics. In theory you can all set the response type or content type (MIME type) of the response to anything you want. Correct me if im wrong about this one. But i havent tried some other MIME types as a response format. So far i only used RAW text, XML and now my favorite JSON.

JSON stands for Javascript Object Notation and no it is not the name of my boss @ familylink.com which is Jason. As I started swimming the pool i soon realized i needed to output structured data back to the requesting page not just a simple hello world. This can be done using a RAW text format in pre formatted HTML form but depeding on how many records you are retrieving this can affect the response time since the server is preparing to give you back a bunch of data. Your next option would be to use the XML format. The good thing about it is when the server gives you data in XML format you can turn this data into a whole object that you can access all it parent, child data. It is a part of web programming called DOM scripting.

A response from the server using RAW text pre formatted HTML (from a firebug console).

A Raw Text response from firebug console

A response from the server using XML format (from a firebug console).

XML format response

The response time varies depending on how much data is sent back to you and how much data is being processed by the server. In the first picture, the total processing and sending of the data in milliseconds is 594 ms. (.5 secs) while the seconds picture in XML format took overall 9906ms or 9.9 Secs. This doesnt mean that RAW text is faster than XML as i stated that it really depends on the processing and sending back of the data. In these examples the second request took 9.9 secs because it is issuing multiple queries in the database to retrieve the needed information while the first request only made 1 query. So it really depends.

Well i am excited to talk about JSON as the output format. Again i must not go into the details telling you about it as i dont really consider myself as a genius about all these stuff. to be brief JSON is a format alternative to the traditional XML format. It is lightweight and parser is readily available on almost all programming languages.

A response from the server using JSON format (from a firebug console).

JSON format

JSON response is smaller than that of the XML output since the tags are now replaced with braces. No tag redundancy like that of the XML and if you already knew the structure of the XML, you already get the idea by just looking at it. That is why JSON is now my choice as server response type. And by the way make sure that you modify the output header and tell the browser that you are sending back JSON format by using the MIME type application/json. You are still going to use responseText in the XMLHttpObject though but the expected response would now be JSON.

I got the data like that now what?

I don’t expect you to present that kind of data to your audience :p. Of course just like XML you parse it or you interpret it to meaningfully present it to your users. its pretty easy using this code below from wikipedia.

var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function (){
   if ( http_request.readyState == 4 ) {
      if ( http_request.status == 200 ) {
        var obj;
        obj= eval("(" + http_request.responseText + ")" );
      }else{
        alert( "There was a problem with the URL." );
      }
      http_request = null;
   }
};

This is the very basic of the XHR or the AJAX request. After you passed the response to the variable “obj” using eval in Javascript it will transform into an object that you can access its node or contents like this parent.child.data really neat. However nowadays you’re not oblige to use the basic code above to make request to the server. There are lots of Javascript framework that does these things for you. I have used prototype,mootools and jQuery so far and they’re really great. The parser is already there for you to use. Thanks to this geniuses we dont have to worry about the other details and get straight into the action. Be warned about all these abstraction stuff, make sure you know the inner workings of this whole thing so you don’t get confused when an errors occurs during your request(s).

So you have decided to use JSON over XML?

[del.icio.us] [DotNetKicks] [Digg] [Facebook] [Google] [MySpace] [Squidoo] [StumbleUpon] [Technorati] [Windows Live] [Yahoo!]

Posted in General Javascript Programming

2 Responses

  1. BJ

    Wow, I didn’t know the Firebug console can do that. How do you set that up?

  2. admin

    For the benefit of all, firebug is a plugin for firefox that is really indispensable for me as a web developer. Everytime you make request to the server, firebug keeps track on all of them. When you click the console tab and make AJAX request, the request will be visible on the console with 3 tabs. The headers, the post data and the server response. This idea is the same for the NET tab when you first load the page. You can actually see the headers of the response with information like accept encoding which is really important for page performance.

    @BJ thanks for that PNG tip in IE which can be found here Serving-PNGs-in-your-website.aspx

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.