Monday, April 18, 2005AJAX with dynamic SCRIPT tags -- revised

At work we have been experimenting with various methods of retrieving data from the server-side. The most traditional AJAX approach is by using the XMLHTTPRequest object (asynchronous or synchronous) as the transfer mechanism and XML to describe the data.
Another method is using JavaScript SCRIPT tags as the transfer mechanism, and JavaScript Object Notation (JSON) or regular JavaScript syntax to "describe" the data.
You can achieve this by dynamically creating JavaScript SCRIPT tags, where the source (src) is a ColdFusion template that generates JavaScript.
I think that this is the easiest and quickest method of AJAX, and it really allows you to reuse your existing business logic quickly.
1. Static JavaScript file dynamically creates a SCRIPT tag via the DOM
2. The source of the SCRIPT tag is the ColdFusion template that dynamically creates the JavaScript code.
As an example, let's retrieve a bunch of artists from the sample artist database that comes with ColdFusion MX. I'll then draw the artists to an existing HTML table using the DOM.
By the way, this code only works in Internet Explorer (but could be easily modified to work in Firefox). Given it is an example, I have a certain license! :)
display.html
This is a sample HTML page that contains the empty table ready for population. Upon first load, the table is automatically populated.
<html>
<head>
<title>JSON Test</title>
<script src="artists.js"></script>
</head>
<body>
<a href="javascript:getArtists()">Call getArtists() method -- appends to table!</a>
<br/><br/>
<table id="artistTable">
<caption>Artists</caption>
<thead>
<tr>
<td>ID</td>
<td>Last Name</td>
<td>First Name</td>
<td>City</td>
</tr>
</thead>
</table>
<script>
getArtists();
</script>
</body>
</html>artists.js
This JavaScript file contains methods that will dynamically create the SCRIPT tag. The src attribute of the SCRIPT tag is the getData.cfm ColdFusion template, which creates the JavaScript data.
The populateUI method (which populates the table with the data) is only called once the SCRIPT tag's readyState has changed to "loaded".
function getDataFromServer(id, url, callback)
{
oScript = document.getElementById(id);
var head = document.getElementsByTagName("head").item(0);
if (oScript)
{
// Destory object
head.removeChild(oScript);
}
// Create object
oScript = document.createElement("script");
var dtRf = new Date();
oScript.setAttribute("src",url + "?rf=" +dtRf.getTime());
oScript.setAttribute("id",id);
head.appendChild(oScript);
if (oScript.readyState!="loaded")
{
oScript.onreadystatechange = function()
{
if (this.readyState == "loaded")
{
eval(callback);
oScript.onreadystatechange = null;
}
}
}
else
{
alert('Cannot load data!');
}
}
function getArtists()
{
getDataFromServer("artistData","getData.cfm","populateUI()");
}
function populateUI()
{
oTable = document.getElementById("artistTable");
// Loop over the data in the JS array, and add to table
for (var i=0; i < aData.length; i++)
{
// Create a new TR element
oTR = oTable.insertRow();
// Create a call for each element in struct
oTD = oTR.insertCell();
oTD.innerHTML = aData[i].artistid;
oTD = oTR.insertCell();
oTD.innerHTML = aData[i].lastname;
oTD = oTR.insertCell();
oTD.innerHTML = aData[i].firstname;
oTD = oTR.insertCell();
oTD.innerHTML = aData[i].city;
}
}getData.cfm
This ColdFusion template performs a query on the artist database. The query is then converted to an Array of Structures (using QueryToArrayOfStructures from cflib.org), and then converted to JavaScript using the CFWDDX tag.
I am not *really* using JSON here. But, by using the bult-in ColdFusion JavaScript conversion functionality in the CFWDDX tag, you achieve the same result, it's just not as light-weight.
<cfsetting enablecfoutputonly="true">
<cfquery datasource="cfartgallery" name="qData">
SELECT *
FROM artists
ORDER BY lastname, firstname
</cfquery>
<cfwddx action="cfml2js" input="#QueryToArrayOfStructures(qData)#" output="jscontent" toplevelvariable="aData">
<cfoutput>#jscontent#</cfoutput>
There you have it! I'm pretty sure this code shall work, and I welcome any comments or improvements. It was put together pretty quickly!

"The most traditional AJAX approach is by using the XMLHTTPRequest object (asynchronous or synchronous). Another method is using JavaScript Object Notation (JSON), and get JavaScript code from the server instead of XML."

That's where I lost my bearings, sorry... XMLHttpRequest is a transfer mechanism (like the initial page request, or an innerFrame refresh), but JON seems a formatting convention, independent of transfer mechanism...?

John, yeah, you are right. I've changed the post a bit so it hopefully makes more sense.

The transfer mechanism in this example is actually the creation of the SCRIPT tag using the DOM. The source of the SCRIPT tag is the dynamically created JavaScript code (arrays of structs, arrays, etc) that can then be used on the client-side.

You're right, JSON is a lightweight formatting convension. The theory is that it should be a lot quicker to dynamically create the SCRIPT tags, and transfer a more lightweight version of the data than by using XMLHTTPRequest and XML.

When the SCRIPT tag is appended to the DOM, the SRC of the SCRIPT tag gets executed.

When the SCRIPT tag is removed from the DOM and then re-added, the SRC gets executed again. You'll notice that I've placed a "rf (refresh)" in the query string so that the browser won't cache the returned file.

In my example as well, the data is refreshed manually by calling the "getArtists" method. You could create a timer in JavaScript to automatically go and get new reminders.

I'm try to use the "on-demand javascript" approach to load '000s records from a dataset as javascript array for display in a grid (ActiveWidgets grid). Using this type of code (actually revised I guess by Jason Levitt in article "Fixing AJAX: XMLHttpRequest Considered Harmful") I find that it works OK in IE6, but as soon as you put the dynamic script tag addition into the function getDataFromServer, Firefox seems to carry on loading the rest of the page before the data has finished downloading. Outside of a function FF loads the data from the new script tag OK, waiting for it to finish before running the rest of the page.

Will, I haven't really seen that article in much depth, but I'll try to help. You would probably be better off using one of the multitude of JavaScript libraries out there to perform asynchronous data delivery. They don't use on-demand JavaScript, but use cross-browser XMLHTTPRequest. You can try MochiKit (http://www.mochikit.com/) or Dojo Toolkit (http://dojotoolkit.org/).

In an up-coming post I will be explaining the principles behind batch delivery of records. For example, instead of kitting 1000's of records at time, you get them in batches, so you can progressively load data.

Dear friend ! 1.We can offer all kinds of wholesale watch. We offer safe delivery and best service,low price and good quality. 2.We have excellent customer service team, which could solve online various problems about wholesale watches we provide in 24 hours.3.We have perfect Logistics system, which guarantees all the ordered replica watches are delivered to you in good shape as fast as possible.Communicate with us.You will be very satisfied! Hope we can do long-term business in near future.

Darryl i want to thank you i am doing web designing and feeling so many difficulty in the AJAX language now after reading your comment i am relaxed and feeling comfortable in using the AJAX..SO thanx for sharing Darryl..

louis vuitton advised abridged the amount of international, but aswell makes the Louis vuitton bags appearance actual altered from accustomed brands, even louis vuitton handbags to match, can not beard the lv out of the appearance the affectionate of takes abroad people's temperament.

The most important difference between a Mini DANIEL BOON format and a regular digital video is that Mini DANIEL BOONE DVD record video and image into a mini DANIEL BOONE DVD COLLECTION disc, whereas others record into a DV Tape. There are a lot of inherent advantages to this.There comes the gate of the uk Tiffany world. Let us begin the marvelous and intriguing journey, with great expectation. silver accessories , just like the sorcerer with some mighty magic in their hands, bring about vivid life to Tiffany sets . These pieces of silver sets look so lovely as some cute pet or fairy, which can communicate with you fluently by heart.

Really trustworthy blog. Please keep updating with great posts like this one. I have booked marked your site and am about to email it to a few friends of mine that I know would enjoy reading..World of Warcraft

What an inspiring article you wrote! I totally like the useful eyeglasses info shared in the article.I like your ideas about glasses online and I hope in the future there can be more bright articles like this from you.I totally agree with you on the point of prescription eyeglasses. This is a nice article for sure.I am glad to read some fantastic ray ban article like this.It has been long before I can find some useful articles about ray ban sunglasses. Your views truly open my mind.Great article, it's helpful to me, and I also like the useful info about sunglasses.Good job for writing this brilliant article of cheap prescription sunglasses.I greatly benefit from your articles every time I read one. Thanks for the prescription sunglasses info, it helps a lot.Bright idea, hope there can be more useful articles about rx sunglasses.Excellent point here. I wish there are more and more bifocals glasses articles like that.Great resources of bifocals eyeglasses ! Thank you for sharing this with us.Your do have some unique ideas here and I expect more progressive eyeglasses articles from you.We share the opinion on progressive glasses and I really enjoy reading your article.You have given us some interesting points on mens glasses. This is a wonderful article and surely worth reading.I appreciate your bright ideas in this men's glasses article. Great work!This is the best mens eyeglasses article I have ever found on the Internet.I love this mens eyewear article since it is one of those which truly convey useful ideas.I really like this men's eyewear article, and hope there can be more great resources like this.

This is the best mens eyeglasses article I have ever found on the Internet.I love this mens eyewear article since it is one of those which truly convey useful ideas.I really like this men's eyewear article, and hope there can be more great resources like this.Thank you so much for sharing some great ideas of cheap eyewear with us, they are helpful.This discount glasses article is definitely eye-opening and inspiring. We share the opinion on glasses and I really enjoy reading your article.I really like this optical article, and hope there can be more great resources like this.This is the best discount eyeglasses article I have ever found on the Internet.Your do have some unique ideas here and I expect more discount eyewear articles from you.I greatly benefit from your articles every time I read one. Thanks for the brille info, it helps a lot.It has been long before I can find some useful articles about brillen. Your views truly open my mind.Thank you so much for sharing some great ideas of kunststoffbrille with us, they are helpful.I appreciate your bright ideas in this kunststoff-brille article. Great work!This gleitsichtbrille article is definitely eye-opening and inspiring. You have given us some interesting points on gleitsichtbrillen. This is a wonderful article and surely worth reading.Good job for writing this brilliant article of fashion brillen.I love this fashion brille article since it is one of those which truly convey useful ideas.Great article, it's helpful to me, and I also like the useful info about ray ban sunglasses online.I am glad to read some fantastic ray ban aviator article like this.Excellent point here. I wish there are more and more ray ban wayfarer articles like that.Bright idea, hope there can be more useful articles about ray ban wayfarer sunglasses.What an inspiring article you wrote! I totally like the useful eyeglasses info shared in the article.I like your ideas about glasses online and I hope in the future there can be more bright articles like this from you.I totally agree with you on the point of ray ban. This is a nice article for sure.Great resources of ray ban sunglasses! Thank you for sharing this with us.

power balance is Performance Technology designed to work with your body's natural energy field. The Hottest Pop Star on earth has teamed up with the Hottest Fashion Accessory: silly bandz is releasing the most popular pack of Silly Bandz to date

That's where I lost my bearings, sorry... XMLHttpRequest is a transfer mechanism (like the initial page request, or an innerFrame refresh), but JON seems a formatting convention, independent of transfer mechanism.guess perfume

Silk scarves are one of the most recognized products across the world. When you attend a dinner,silk scarves add the elegance and grace to a dress.A cashmere scarf is one of the most important tools of the fashion world because of its versatile ability to just be perfect and suitable with just about any outfit that you could think of.The wool scarves are soft, warm and always fashionable, so in the cold winter, they will be a good choice for you.Silk scarves are just widely used for women and men. Dress designers are coming up with Silk scarves that go with the figure of young women as well. They do not fit significant and ungainly exactly how most males prefer their Silk scarves. Silk scarves for women are created to fit a woman’s body to still highlight her body. The urban look with the Silk scarf compliments both ladies and men any time wearing a great pair of denims and certain fly shoes.

I admire the way you express yourself through writing. Your post is such a refreshing one to read. This is such an interesting and informative article to share with others. Keep up the good work and more power. Thanks!

An impressive share, I simply given this onto a colleague who was doing somewhat evaluation on this. And he in reality bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading extra on this topic. If possible, as you turn out to be experience, would you thoughts updating your weblog with extra details? It is extremely useful for me. Huge thumb up for this blog put up! Solar Panels Cost

I finally found one post which is informative and which has provided genuine information for the readers. I really liked the way writer has thrown some light on unhidden facts. Great job in deed!Orange County photographers

Yemek Tarifleri Thanks for this post – I have struggled with this as I have NO comments yet on my blog and in some ways feel badly about that (until i read your posts about this) and yet I see there is more that I can do. thankss.

Well… actually I just love the way the article has been formed and concluded. I think other fresh writers should learn from you and write just like you. The way you have given information on the subject is just too wonderful and amazing.Cheap Viagra

Hi, I appreciate the information that you have provided in the post. It is worth noting and I really liked the presentation as well. I will surely come back for more of interesting posts. website design

Man I like your post and it is so good and I am definetly going to save it. One thing to say the Indepth analysis this article has is trully remarkable.No one goes that extra mile these days? Bravo!! Just one more tip you canget a Translator for your Worldwide Audience !!!

Easily, the publish is really the greatest on this laudable topic. I concur with your conclusions and will thirstily look forward to your future updates. Saying thanks will not just be sufficient, for the fantastic lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Solid work and much success in your business enterprise!

I absolutely adore reading your post, the form of writing is extraordinary.This post as usual was informative, I have had to bookmark your blog and subscribe to your feed in ifeed. Your site looks great.http://www.trainingtampa.com

This is an excellent point. Many bloggers will get involved in intelligent conversation on your blog because they know that they will get a link back to their own blog. When the link takes you to Facebook, it becomes much less appealing.korumbusiness card printing miami

If you want to buy xanax online then I think you are at right place mycare pharmacy is one of the best pharmacy . Here you can buy medicines at very cheap rates as like buy ritalin online and many more .

uggs clearance A different characteristic from the net is searching mall clubs which you'll join to ensure that you'll be able to get your Ugg boots through the virtual Uggs Outlet buying mall plan and that far too at a low cost. All purchases could be designed utilizing credit cards and in the handful of days time, it is possible to obtain the really pair that you simply requested and compensated for at your doorstep ugg boots clearance.

i have heard about ajax and was just thinking that how will work. how will i be able too use it.see your blog give me the solution for this problem.great presentation of the AJAX now i can see how it looks.thanks for the share.

Truly a nice work! Greatest post I have ever seen! Thank you for sharing it! Have a good day!The Kettlebell Shop is Australias premier online supplier of quality Kettlebells at great prices. $20 flat fee delivery to major cities!! We deliver Australia wide.More info please visit at our website:http://www.thekettlebellshop.com.au./

http://foodscienceproductdevelopment.com/"Beverage Consulting"Providing professional and qualified experience for the food and beverage development industry Food Science Chef provides high quality and cost-effective new food product and everage development services and qualified experience for the food and beverage development industry.

way of writing the post. Now you make it easy for me to understand and implement expressed. I really like to appear back over a typical basis, post a lot more within the topic. Thanks for sharing good information. keep writing about well and good information !!!..dc locksmith

Great loved it, I concur with your conclusions and will eagerly look forward to your future updates. The usefulness and significance is overwhelming and has been invaluable to me! keep it up bro ! Thanks for sharing information.

Great inof... thanks for the effort in explaining all of this!Providing the best value in Logo, Special event and Personalized imprint Golf balls!.logo golfballs, personalized golfballs, gift golfballs, event golfballs.More Info.. Please visit at our Website: http://www.bigeventgolf.com/

Great information !!!thanks for sharing this with me.In fact in all posts of this blog their is something to learn .Your work is very good and i appreciate your work and hopping for some more informative posts . Again thanks for sharing.