Etcetera

Tuesday, June 5, 2007

Generic AJAX Object

Posting a code that you can use in your page to implement AJAX. Its is not a full fleged javascript object yet, but I feel its good enough to start.


function ajaxcore(){
var req; // the request object
var cbfn; // name of the callback function

this.initRequest = function(){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
throw new Error("XMLHttpRequest not supported");
}
}

// Call this method for processing your request.
// arguments:
// cbFunName - name of callback function that you will handle
// url - servlet URL
// todo..
// provide additional argument that would be a
// form object which would be parsed
// and then given to the server for processing.

this.doCompletion = function(url,cbFunName) {
if ("undefined" == cbFunName){
alert ("Inappropriate Callback function specified. Aborting server
call without further action.");
return;
}
cbfn = cbFunName function () { };

try{
this.initRequest();
}
catch (e){
alert ("Unable to create XML request object.")
}

if (req != null){
req.onreadystatechange = function() {
if (null != req ){
if (req.readyState == 4){
cbfn (req.responseText,req.responseXML,req.readyState,req);
}else {
cbfn (null,null,req.readyState,req);
}

}
else{
//todo...
}
}
req.open("GET", url, true);
req.send(null);
}
else{
alert ("You are probably using a primitive browser.");
}
}
}// Main End