Monday, February 8, 2010

How to Handle Session Expire in Ajax Call (Prototype Framework)

Steps:
1. Call is made to server using XMLHttpRequest either get or post method
2. Check string token like "session expired" or "sessionexpired" the result data. If so then it indicates that session is expired.
3. If session expired then redirect it to the Session Expire Page using following code:
var sessionExpiryURL="/global/sessionExpired.jspx";
window.location=sessionExpiryURL;


Sample Codes:

Note: Sample code uses prototype framework.

Script uses handling Session Expire:
var sessionExpiryURL="/global/sessionExpired.xhtml";

/*
    The following method checks if the session has expired or not
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
*/
function isSessionExpired_OnResponseText(ajaxResponseText){
    if (ajaxResponseText != null ){
        var lclAjaxResponseText = ajaxResponseText.toLowerCase();
        if (lclAjaxResponseText.indexOf("session expired") >=0 || lclAjaxResponseText.indexOf("sessionexpired") >=0 ){
            return true;
        }
    }
    return false;
}
/*
    The following method checks if the session expired and redirects to session expiry  page
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
*/
function handleSessionExpiry_OnResponseText(ajaxResponseText){
    if(isSessionExpired_OnResponseText(ajaxResponseText) == true){
            window.location=sessionExpiryURL;
    }
}

/*
    The following method checks if the session has expired or not
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
*/
function isSessionExpired(ajaxResponseObj){
    if (ajaxResponseObj!= null ){
            var contentText =ajaxResponseObj.responseText;
            return isSessionExpired_OnResponseText(contentText);
    }
   
}

/*
    The following method checks if the session expired and redirects to session expiry  page
    Pre: Applicable for Ajax call only and the ajaxResponseText must pass the responseText from the AJax call
   
*/
function handleSessionExpiry(ajaxResponseObj){
    if (ajaxResponseObj!= null ){
            var contentText =ajaxResponseObj.responseText;
            return handleSessionExpiry_OnResponseText(contentText);
    }
}

Script uses to post Ajax Call:

var jScript = Class.create();
    jScript .prototype =  {
    initialize: function()
    {
          // Initialization Stuff, It is called before calling any mothod of jScript
    },


/* funtion defination
@ URL - URL to be submitted to server
@ params-Associative array (Hash) to carry data from client to server
@ sourceObj- Ideally onchange of source object event; it posts the ajax request
@ targetObj- Ideally  targetObj is the placeholder for the response like populating some data into it.
/*
post: function(URL, params, sourceObj, targetObj) {
        var url = strURL ;
        var responseText = "";
        new Ajax.Request(strURL, {
                parameters: parameters,
                method:'post',
                onSuccess:function(transport) {
                    try {
// Algorithm uses to extract data from response and populate to the targetObj
                        }
                     }catch(e) {
                            if(isSessionExpired(transport)==true) {
                                handleSessionExpiry(transport);
                                return;
                            }
                            alert("System Error" );
                     }
                },
                 onFailure:function(transport) {
                    alert("An  error occurred");
                    alert("Error occurred: " + transport.responseText);    //Debug purpose only
                    //TODO handle errors
                 }
        });
    },


//AJAX Function
    loadStates: function (){
   var sourceObj = $('countryName'); // country name selected in dropdown
    var targetObj = $('stateNames'); // dropdown list box to  hold state names
    var parameters = new Hash();

    var strURL="../Country/getStates.xhtml"; // Servlet to provide state names
    parameters['countryName'] = sourceObj.value;
    parameters.set('ajaxParam', '1');
    this.post(strURL, parameters,  sourceObj , targetObj );
    }
};

jScript .Initializer = function() {
        jScript = new jScript ();
}

Event.observe(window, 'load', jScript .Initializer);