Handling expired sessions in AJAX applications with jQuery

Nowadays quite lots of sites are AJAXy, especially their back-end part. This introduces one interesting issue with sessions and password protected areas. Typical scenario is: password protected URL initiates a server-side check for valid user is logged in or in other case redirects to login page. What happen when session is expired by timeout? Session data is wiped from the server, so already logged user becomes like a just comer. Next request to the server will eventually redirect him back to login dialog. But not in case of AJAX. Usually AJAX requests are written in the way not to support sudden session break and this situation can lead to a very unpredictable behavior. How to fix it quick? Good news are If you use jQuery (don't you ???) for making AJAX calls, it is very easy to fix. Luckly there is an event that can intercept all AJAX requests to one global handler first, where decision can be made. In this example, server side PHP shows login dialog in case user session is expired. On each AJAX requests returned data is checked agains unique login form name and does redirect to login dialog without ruining interface or data.
$(document).ajaxSuccess(function(evt, request, settings){
   if (request.responseText.indexOf('UserLoginForm') != -1)
      location.href="/login";
});
Simple and handy to fix any existing site!

1 comment

Leave a Reply

Your email address will not be published.