Javascript AJAX function
I’ve been using AJAX for awhile but had been always using JQuery’s AJAX function which most of the time does the job very well and very elegantly however I started having problems with it on Internet Explorer so had to use a backup method (although also using JQuery) and then more recently when I need to wrap a Javascript application up a standalone application using the rather nifty www.htmlexe.com I found that the JQuery AJAX functions just stopped working completely so had to go back to brass tacks and actually learn how to do AJAX from scratch which to be honest I should have done from the start and has given me a better appreciation from the technology. I’ve written a new AJAX function in Javascript, it’s mostly the same version as on W3Schools and everywhere else on the web but here it is should anyone else be looking for something similiar:
// Creates a runs an AJAX request
// Parameters: url:string, callbackFunction:function;
// Returns: void;
function ajax(url, callbackFunction) {
var xmlHttp;
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e) {
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
callbackFunction(“ERROR: AJAX not supported”);
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
callbackFunction(xmlHttp.responseText);
}
}
try {
xmlHttp.open(“GET”, url, true);
xmlHttp.send(null);
} catch (e) {
callbackFunction(“ERROR: Cannot access URL”);
}
}