On demand javascript “an AJAX alternative”

April 28th, 2008   Filed Under Good to know, Javascript, Technology, Tips & Tricks, json  

AJAX … sounds to be very sophisticated, powerful buzzword for last 3 years which helps in data transfers done without reloading the web page.
But if we really think, we hardly use the ‘X’ part of AJAX; Meaning we do not pull xml data from the server but we generally pull some JSON data or strings and then process them and manipulate the displays.
If you think we don’t use the ‘A’ part of it too most of the times. I mean the Asynchronous part.
So what we use AJAX is for downloading some strings without refreshing the page.
If that is all what we need, then we can opt for a simpler solution called “On-demand-javascript”.
It is very simple to understand.
Create a script block with a src set to some server side dynamic entity(.asp, .jsp, servlet, .php etc) which in turn will send some JSON data in turn. For example:

<script type="text/javascript" id="dataBus" src="/myServlet.do?action=init"></script>

The above script node may establish a connection with the browser and set a session cookie.
Depending upon some event on the page, we can use the dataBus to pull some data from the server for us(it will just work like a pipe for us):

document.getElementById('dataBus').src="/myServlet.do?action=transfer&type=address&dateTime=utf-6556554351516";

The above code may pull some JSON data for us and once it is loaded our subsequent javascript code can use the received data.

The features/benefit of this approach would be:

  1. No cross domain constraints.
  2. Synchronous delegation.
  3. Already evaluated JSON data.
  4. You need to just place your data and don’t break your head in making-up a valid javascript object even if it is a string.

There can be a well lot of patterns for using the transported data and making data delivery secure around this approach.

But I am not telling you to forget AJAX. Because when you need to send some information using post method to your own server, this trick will not help you.

So the next time when you plan for some AJAX data pull, just consider this approach as an option and compare which one is worth for you.


Comments

Leave a Reply