I know there are a lot of javascript/ajax libraries out there such as prototype, but what if you just need the bare minimum? I don’t like lugging around features I don’t use, so I wrote this really handy little object. As I said, this thing does the bare minimum.
//handler has the signature: methodName(responseTxt)
function AJAX(handler){
function _handleTheAx(req, handle) {
if (req.readyState == 4) {
handle(req.responseText);
}
}
function call(url){
var req = this.reqobj;
if ((req.readyState == 4 || req.readyState == 0)) {
req.open("GET", url, true);
req.onreadystatechange = function() {_handleTheAx(req, handler);};
req.send(null);
}
}
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
return null;
}
}
this.call = call;
this.handler = handler;
this.reqobj = getXmlHttpRequestObject();
}
So how do you use it? Easy:
function theResponse(respTxt){
alert(respTxt);
}
function doSomethingCool(){
teHajax.call('url/to/my/script.php');
}
var teHajax = new AJAX(theResponse);
You would just have to call doSomethingCool() and the response would show up in theResponse(). Yay! That was easy wasn’t it!