Last Updated: February 25, 2016
· tb

Handling AJAX errors

If you use AJAX in your web app, you might run into situation when user open multiple instaces of your app in tabs and logouts on one of them. Then all other open pages AJAX calls will result in HTTP status codes: 401 Unauthorized and/or 403 Forbidden.

Adding following jQuery AJAX global event handler:

$(document).on('ajaxError', function(event, xhr) {
  if (xhr.status === 401 || xhr.status === 403) {
    alert("Sorry, your session has expired.");
    window.location.href = "/login";

will warn user there was an AJAX authorization issue and redirect user to login page.