I have been using a simple Ajax Util, for my Ajax calls for places where I just need simple AJAX calls and don't want to use any of the JS libs. This is how you use the Util
function ajexTest(){
var ajax = new AjaxUtil();
ajax.url= "http://www.google.com";
ajax.formObj=document.searchCustomerForm;
ajax.waitCallback = function(){
//do something while waiting
}
ajax.scucessCallback = function(text){
//do something on success
}
ajax.doPost();
}
And following is AjaxUtil code:
/**
* Author:Anurag Kumar Jain
* Date: July 11, 2007
**/
function AjaxUtil(){
//alert("creating AjaxUtil);
this.req=this.init();
this.url="";
this.parameters="";
this.async=true;
this.formObj;
this.scucessCallback=null;
this.ajaxCallback=null;
this.errorCallback2=null;
this.errorCallback=function(responseText){
//alert(responseText);
document.location.href = "error.jsp";
}
var me = this;
this.req.onreadystatechange = function() {
//alert("in processRequest readyState = " + ajaxRequest.readyState);
// readyState of 4 signifies request is complete
if (me.req.readyState == 4) {
// status of 200 signifies sucessful HTTP call
//alert(ajaxRequest.responseText);
if (me.req.status == 200) {
//alert("ajax Callback Function is: " + ajaxCallback);
//alert(me.req.responseText);
//alert(me.req.status);
if (me.scucessCallback) me.scucessCallback(me.req.responseText);
}else{
//alert(me.req.status);
if(me.errorCallback) me.errorCallback(me.req.responseText);
if(me.errorCallback2) me.errorCallback2(me.req.status, me.req.responseText);
}
}
}
}
AjaxUtil.prototype.init = function() {
//alert("initializting request");
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
};
AjaxUtil.prototype.doPost = function () {
//alert("in doPost");
//alert(this.url);
this.req.open("POST", this.url, this.async);
this.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//req.setRequestHeader("Content-length", this.parameters.length);
//this.req.setRequestHeader("Connection", "close");
this.parameters+=getFormValues(this.formObj,null);
//alert(this.parameters);
//alert(this.url); alert(this.parameters);
this.req.send(this.parameters);
if(this.waitCallback) this.waitCallback();
};
AjaxUtil.prototype.doGet = function(){
//alert("in doGet");
//alert(this.url);
this.req.open("GET", this.url, this.async);
this.req.send(null);
if(this.waitCallback) this.waitCallback();
};
function getFormValues(fobj,valFunc){
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < cmd =" valFunc" val =" eval(cmd)" str =" str.substr(0,(str.length">
No comments:
Post a Comment