// | ########################################################################## |
// |-------------- powered by Djingle -------- AJAX functions ----------------- |
// | ########################################################################## |
var ICON_OK='
';
var ICON_KO='
';
var LOADING='
';
var ajaxObject = null;
function _array2String(myArray) {
var tmp="";
for (var k in myArray) {
tmp=tmp+k+"="+myArray[k]+"&";
}
return tmp;
}
function ajaxRequestManager(URL, params_array, method) {
this.URL=URL;
this.paramsArray=params_array;
if (method) this.method=method;
else this.method='GET';
this.outputFormat='json';
this.debugMode=false;
this.lastError='';
this.lastErrorMessage='';
this._callAJAX = function(asynchrone) {
if(window.XMLHttpRequest) // Firefox
ajaxObject = new XMLHttpRequest();
else if(window.ActiveXObject) // Internet Explorer
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
else {
// XMLHttpRequest unavailable
alert("Your browser does not support XMLHTTPRequest.");
return;
}
var data = "";
for (var name in this.paramsArray) {
if ( data.length>0 ) data += "&";
data += name + "=" + encodeURIComponent( this.paramsArray[name] );
}
if(this.method == "POST") {
ajaxObject.open(this.method, this.URL, ((asynchrone)?asynchrone:false));
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); // UTF-8 is optional but just in case...
ajaxObject.send(data);
} else if(this.method == "GET") {
ajaxObject.open(this.method, this.URL+"?"+data, ((asynchrone)?asynchrone:false));
ajaxObject.send(null);
}
return ajaxObject;
};
this.onSuccess = function(result) {
return true;
};
this.onError = function(result) {
this.lastError=result['error'];
this.lastErrorMessage=result['error_message'];
return false;
};
this._isJSON = function(str) {
var test1=/^\s*$/.test(str);
if (test1) return false;
str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
//alert('AFTER REPLACE:' + str);
return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
};
this.processRequest = function(asynchrone) {
//add custom params
//this.paramsArray['_output']=this.outputFormat;
this.paramsArray['_output']='json';//force json to force javascript redirect
if (this.debugMode)
alert("Ajax call: "+this.URL +"?"+ _array2String(this.paramsArray));
var _response = this._callAJAX(asynchrone);
if(_response.readyState == 4) {
var myAjaxResponse=_response.responseText;
if (this.debugMode)
alert("Ajax script answered text: "+myAjaxResponse);
//check if session was not lost (nor rights mismatch)
var _result = false;
if (this._isJSON( myAjaxResponse ) ) {
_result = JSON.parse( myAjaxResponse );
if (_result['result']!='ok') {
switch(_result['error']) {
case '10':
document.location='http://www.djingle.fr/index.php?module=Home&class=Home';
break;
case '11':
document.location='http://www.djingle.fr/index.php?module=AccessManager&class=AccessManager&action=displayRightsMismatch';
break;
}
}
}
if (this.outputFormat=='json') {
//force parse (cause _isJSON is not 100% perfect)
_result = JSON.parse( myAjaxResponse );
if ( _result ) {
if (_result['result']=='ok') {
return this.onSuccess(_result);
} else {
return this.onError(_result);
}
} else {
var tmp=new Array;
tmp['error']=100;
tmp['error_message']='Empty Json string';
return this.onError(tmp);
}
} else {
//just return result
/* if (this.outputFormat=='html') */
return myAjaxResponse;
}
}
};
}
//usefull fct for quick standard ajax use cases
function ajaxAction(_module, _class, _action, other_data, notif_layer, debug_mode) {
if (notif_layer) {
var l=new LAYER(notif_layer);
l.WriteInto(LOADING);
}
var data=new Object;
if (other_data)
data = other_data;
data['module']=_module;
data['class']=_class;
data['action']=_action;
var myAjaxInterface = new ajaxRequestManager('http://www.djingle.fr/index.php', data);
myAjaxInterface.debugMode=debug_mode;
myAjaxInterface.onSuccess = function(result) {
if (notif_layer) {
l.WriteInto(ICON_OK);
setTimeout('document.getElementById("'+notif_layer+'").innerHTML="";',1000);
}
return true;
};
myAjaxInterface.onError = function(result) {
if (notif_layer) l.WriteInto(ICON_KO+' '+result['error_message']+' ('+result['error']+')');
return false;
};
myAjaxInterface.processRequest(false);
return false;
}
//################################################## jQuery Style ####################################################
//################################################## jQuery Style ####################################################
//################################################## jQuery Style ####################################################
var SERVER_URL = 'http://www.djingle.fr/';
var jQueryService = null;
AjaxjQueryManager = function( url )
{
//needs a function called _log
this.svcUrl = url;
this.debugMode = false;
this.displayAjaxResponse = false;
this._array2String = function (myArray) {
var tr='foo=foo&';
for (var k in myArray) {
tr+=k+"="+encodeURIComponent(myArray[k])+"&";
}
if (this.debugMode) tr+='debugMode=true&';
return tr;
};
this._handleSuccess = function( resObj, successHandler, errorHandler )//function( xhr, status, handler )
{
if ( this.debugMode ) {
_log('Ajax success', false,
(this.displayAjaxResponse ? JSON.stringify(resObj,null,'\t')+"\n\n" : "") + // TODO format
(resObj.debug ? "Debug data:\n"+resObj.debug : "") );
}
if ( !("result" in resObj) ) {
if ( resObj.errorCode == 10)
document.location=SERVER_URL+'index.php?module=Home&class=Home';
else if (resObj.errorCode == 11)
document.location=SERVER_URL+'index.php?module=AccessManager&class=AccessManager&action=displayRightsMismatch';
else if ( resObj.errorCode ) {
_log("API error ("+resObj.errorCode+"): "+resObj.errorMsg, true);
if ( errorHandler )
try { errorHandler(resObj/*.errorMsg ?*/, "api_error", resObj.retry); }
catch(e) { dumpError(e, "Exception in ajax error handler"); }
} else {
_log("API invalid response", true, JSON.stringify(resObj,null,'\t'));
if ( errorHandler )
try { errorHandler(resObj, "api_exception", false); }
catch(e) { dumpError(e, "Exception in ajax error handler"); }
}
} else {
if ( successHandler )
try { successHandler(resObj.result); }
catch(e) { dumpError(e, "Exception in ajax success handler"); }
}
};
this._handleError = function( xhr, status, errorHandler )
{
_log('Ajax '+status, true, xhr.responseText); // TODO not enough, find error description if status==error
if ( status != "abort" )
if ( errorHandler )
try { errorHandler(xhr.responseText, status, false); }
catch(e) { dumpError(e, "Exception in ajax error handler"); }
};
//TODO : see http://api.jquery.com/jQuery.getJSON/
// onSuccess : function( result object )
// onError : function( result(obj/string), status(string), isRecoverable(bool) )
this._ajaxCall = function( params, onSuccess, onError )
{
var paramsStr = this._array2String(params);
if (this.debugMode) _log("Ajax call", false, paramsStr);
return $.ajax({
method: "get",
url: this.svcUrl,
data: paramsStr+'_output=json',
dataType: "json",
context: this,
//complete: function(xhr, status) { this._handleResponse(xhr, status, onComplete); },
success: function(res) { this._handleSuccess(res, onSuccess, onError); },
error: function(xhr, st, except) { this._handleError(xhr, st, onError); }
});
};
}
function ajaxjQuery(tModule, tClass, tAction, params, onSuccess, onError, debugMode, loadingDiv, loadingStr) {
if (loadingDiv) {
$('#'+loadingDiv).html(loadingStr);
}
jQueryService = new AjaxjQueryManager(SERVER_URL+'index.php?module='+tModule+'&class='+tClass+'&action='+tAction);
if (debugMode) jQueryService.debugMode=true;
if (debugMode===2) jQueryService.displayAjaxResponse = true;
return jQueryService._ajaxCall(params, onSuccess, onError);
}