Ajax requests when session timed-out

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.

Solution

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

Mersi ME!

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 129 other followers

%d bloggers like this: