I’m : a web and mobile developer based in the Manning Valley, Australia.

Handling session expiration in Ajax requests

If you're building a web application today there's no getting away without including Ajax functionality. But when you're dealing with snippets of HTML coming down the wire for injection in the page how do you deal with cases where the session expires? The last thing you want is to insert some generic login page where a HTML snippet was meant to have been!

If you're using jQuery.ajax() then you're in luck as since version 1.5 the statusCode method has been added. It contains functions that will be called when certain HTTP response codes are received and is exactly what we're looking for. In my case I used jQuery.ajaxSetup() to set the following defaults for Ajax requests:

  statusCode: {
    401: function() {
         * Here you'd handle what happens when you receive a 401 response code.
         * Perhaps you'll pop up an alert or redirect the user to a login page.

Then in my PHP code when I detect the some has to login I do the following:

    class ErrorController extends Zend_Controller_Action
         * Standard error page for access denied scenarios
        public function deniedAction()

As long as you correctly set the response code it'll be picked up by the Ajax request and you can correctly handle the scenario there.