Handling XmlHttp Asynchronous Callbacks

Wednesday, June 29th, 2005

Sometimes you stumble across a piece of code that uses a totally obscure but at the same time supremely simple implementation. This one relates to XmlHttpRequests, or asynchronous web requests, or AJAX, or whatever you feel like calling it. Basically variations on the XmlHttp theme allow you to make a call to one web page from another without the dreaded page refresh. Nothing particularly exciting there. This particular approach however is pretty funky. Basically it makes use of the Javascript eval keyword to physically process the result from the request. This means that the data you return has to be valid Javascript (e.g. alert('Hello World'); or similar), but that’s not necessarily a bad thing.

Imagine for example you have a page with a table of database records displayed on it. If you want to retrieve one more record (old school style), you’d usually have to refresh the whole page. In this new approach, we’d have some sort of client-side function that added a new row (addRow(myRowData)). Using the method below, we could call a page that retrieves a row from the database, and returns as output a string like "addRow(newRowData);". The code retrieves this string, then ‘eval’s the string, which results in the addRow function being executed. Funky? I think it is.

// submit a string using XMLHTTPRequest
function getXML(destination,str)
{
var doc = null
if (typeof window.ActiveXObject != ‘undefined’ )
{
doc = new ActiveXObject(“Microsoft.XMLHTTP”);
doc.onreadystatechange = function () {
if (doc.readyState == 4 && doc.status < 300) eval(doc.responseText);
}
}
else
{
doc = new XMLHttpRequest();
doc.onload = function () {
if (doc.readyState == 4 && doc.status < 300) eval(doc.responseText);
}
}

doc.open( “POST”, destination, true );
doc.send(str);
}

[Credit to JPSpan]

Tags: ,

Comments are closed.

Logo
Post thumbnail Video: LASERS!
Who doesn’t love lasers? Favourite tool of the James Bond villian, and weapon of choice [...]
Post thumbnail Video: Smartphone Roundup
With the recent launch of Apple’s iPhone 4, it’s time to do a once-over of [...]
Post thumbnail Video: Gadgets for Grandparents
Grandparents and gadgets don’t really go together, but this week on TVNZ Breakfast I took [...]
Post thumbnail Review: Kick Ass
I don’t usually review movies, but after giving two copies of Kick Ass away [...]
Post thumbnail Video: LASERS!
Who doesn’t love lasers? Favourite tool of the James Bond villian, and weapon of choice [...]
Post thumbnail State of the Android NZ Nation
Despite the bagging, I really do think Android is pretty damn awesome. I’ve spent the [...]

Enter your email address:


Delivered by FeedBurner