Raymond Camden recently asked on his blog How can you timeout a session in an Ajax-based application?. Most of the comments on the entry relate to doing some kind of server-ping, but my suggestion would be to just let your application tell your Ajax code when the session actually expires.
The concept is to use HTTP response headers to inform your Ajax request when the session has actually expired. This allows you to do everything in one single call, without having to worry writing other code. Besides you should be adding some failure code to your Ajax calls anyway, so this fits right in with good Ajax practices.
There are two basic approaches you can take. Using a "custom" response header or sending back HTTP status code to indicate the user is no longer authorized to view content.
I've put together an example page that shows off how you can implement either of the techniques.
In my HTTP Status Code example I use a 403 - Forbidden to indicate when the user's session has expired—which fits in nicely with the existing HTTP specification (using a 403 will not prompt the browser to reauthorize the user. You could use a 401 HTTP status code if you wanted to force your use to log back in.)
In my Customer HTTP Response Header example, I just pass back to the browser a customer response header of "sessionState" and then use the XHR's native getResponseHeader() method to retrieve the value of the header. You can then take appropriate action based on the header's value.
I've tried to keep the examples very basic and I stuck to just the guts of the technique. Obviously, you'd still need to implement code around this to actually notify the user that their session is expired or to get them to re-login.
Comments for this entry have been disabled.