Now a day most of the applications are running on AJAX. We are making huge use of AJAX to provide rich internet experience. Think of a situation, where your application is password protected. For each http request we make to server, it is being checked against session existence. If session has been expired then the user is forwarded to login page. This goes fine for http requests. But if it is an AJAX request, then just like http request, if session has been expired, it is also forwarded to login page. So if you are directly showing AJAX response in browser, then in place of your expected response you will show the login page content in your browser. And if you would be fetching data of any expected format, then it would throw JavaScript error. To fix this issue, I found out one way, which I feel will be useful for most of the developers of different languages.
Let me first describe the logic that I have devised and then will practically take you through the code.
My Logic for this:
In server side, we can set one page header for the page, whose content is coming through AJAX response wrongly. This is the page, which is redirected to, upon session expiry. Here it is login page.
In client side, we need to check the same header value in AJAX response. If it is found to be there, then we can assume, session has already expired and you need to alert the end user of this and gracefully redirect to login page. Now let’s take a walk through the code for the same.
Server side coding(Here in ColdFusion):
// Setting page header with name as timeout and value as 1
Place the above line in login.cfm page.
JavaScript code(AJAX request section):
//This method makes AJAX call var makeAjaxCall = function(){ $.ajax({ type: "get", url: "components/ajax_component.cfc?method=getTime",//Call to your choice file in server success: function(response,status,xhr){ //Call method to check for session sessionCheck(xhr); //Go for your stuffs here console.log(response); }, error: function(){//Code to run on error alert("Some error happened"); } }) } //This function will check response header and will redirect to login page var sessionCheck = function(xhr){ //Checking for response header, that we have set from server side if (xhr.getResponseHeader('TIMEOUT') == "1") { //Redirecting to login page alert("Your session has been expired. You will be redirected to login page soon."); window.location.href = " /login.cfm"; } }