/* Written by Shay Jacoby (s-online.co.il) */
AJAX = {
xmlHttp:'',
targetObject:null,
outputFormat:'XML',
init : function(methodType, url, callback, params, targetObject, outputFormat){
AJAX.xmlHttp=AJAX.getXmlHttpObject();
if (AJAX.xmlHttp==null){
alert ("Your browser does not support AJAX!");
return;
}
if (methodType=="GET" && params!=null){
url = url + "?" + params;
}
if (outputFormat!=null)
AJAX.outputFormat = outputFormat;
AJAX.targetObject = targetObject;
AJAX.xmlHttp.open(methodType,url,true);
if (methodType=="POST" && params!=null){
if (outputFormat=="JSON"){
AJAX.xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//Convert params to Json format
params = AJAX.toJsonParams( params );
}
else {
AJAX.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.xmlHttp.setRequestHeader("Content-length", params.length);
AJAX.xmlHttp.setRequestHeader("Connection", "close");
}
}
//not tested:
//AJAX.xmlHttp.setRequestHeader("Pragma", "no-cache");
//AJAX.xmlHttp.setRequestHeader("Cache-Control", "no-cache");
AJAX.xmlHttp.onreadystatechange=function(){AJAX.stateChanged(callback)};
AJAX.xmlHttp.send(params);
},
stateChanged : function(callback){
// Returns the status of the request:
// 0 uninitialized, 1 loading, 2 loaded, 3 interactive, 4 complete
if (AJAX.xmlHttp.readyState==4){
//purposes we are only interested in OK (200) response.
if (AJAX.xmlHttp.status == 200){
switch(AJAX.outputFormat){
case "JSON":
if (callback) callback(AJAX.xmlHttp.responseText, AJAX.targetObject);
break;
case "XML":
if (callback) callback(AJAX.xmlHttp.responseXML, AJAX.targetObject);
break;
}
}
else {
// there was a problem with the request, for example the response may
// be a 404 (Not Found) or 500 (Internal Server Error) response codes.
alert('ERROR: ' + AJAX.xmlHttp.statusText + ' (' + AJAX.xmlHttp.status + ')');
return;
}
}
},
//method: Convert parameters to Json Format e.g. {"param1":"param1Value", "param2":"param2Value"}
toJsonParams : function(qStr){
if (qStr==null || qStr.length==0)
return "{''}";
var output = "{";
var params = qStr.split("&");
for (i=0;i<params.length;i++) {
var prmArr = params[i].split("=");
output += "\"" + prmArr[0] + "\"";
output += ":";
output += "\"" + prmArr[1] + "\",";
}
if (output.indexOf(',' > 0))
output = output.slice(0, -1);
output += "}";
return output;
},
getXmlHttpObject : function(){
AJAX.xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari, IE7
AJAX.xmlHttp=new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try{
AJAX.xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
AJAX.xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return AJAX.xmlHttp;
}
}