Using jQuery ajaxError to Automatically Handle Session Expiration and Server Side Errors

A question I get asked a lot is “What is the best way to check for expired sessions in an Ajax application”. A lot of developers end up polling the server every few minutes to validate the users session is still a live. This is a messy approach that has a low probability of actually catching an expired session. Outside of the server pushing these notifications to the client the next best solution is to become familiar with jQuery ajaxError.

JQuery’s ajaxError is automatically called whenever an XHR request completes with an error. If your application is returning proper HTTP codes then we can easily look at the status codes to determine what types of errors to display or actions to perform:

 

In this example I am doing an additional request after a 403 Forbidden error is received to a controller action on the server that checks to see if the users session is still valid. If the session is no longer valid then I redirect to a login page. I’ve also included some additional logic to handle 500 errors.