Handling XmlHttp Asynchronous Callbacks

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.
[code lang=”javascript”]
// 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]

Leave a Reply

Your email address will not be published. Required fields are marked *