If you use AJAX in web applications which are running sessions, I am sure that you have encountered a situation where an AJAX call to the server doesn’t meet its target because the session has expired.
Normally when a session expires, the current user is logout and redirected to the login page. An AJAX request will bring back the login page as its response.
Usually when writing AJAX requests with $.get , $().load or $.post we include callback functions to handle successful or unsuccessful responses.
The response when the session has timed out is the full login page with its entire markup. In the callback, you can include code to detect this but then you would have to write this code in all AJAX methods used throughout your app which is not right.
We can include and call the function below in a script that is loaded in all pages. Every time there is an AJAX call to the server, this function will run.
We can put a unique identifier on the login page say ‘L0g1n’ which is then matched with all AJAX request responses. If a match is found, the function redirects to the login page.
A brief description of what is happening in the above function:
$().ajaxStart registers a handler to be called when the an AJAX request begins.
$().bind attaches the ajaxComplete to the document element
ajaxComplete registers a handler to be called when an AJAX request is complete. Each time ajaxComplete handlers are invoked, they are passed three parameters the event object, the XMLHttpRequest object and the settings object used in the creation of the request hence the function(event, xmlHttprequest, ajaxOptions)
Like my post? Please support me by clicking on the Mersi button