How can I elegantly handle devise's 401 status in AJAX?

$(document).ajaxError(function (e, xhr, settings) {
        if (xhr.status == 401) {
           $('.selector').html(xhr.responseText);
        }
    });

This is the solution I chose for now (in CoffeeScript syntax):

$ ->
  $("a").bind "ajax:error", (event, jqXHR, ajaxSettings, thrownError) ->
    if jqXHR.status == 401 # thrownError is 'Unauthorized'
      window.location.replace('/users/sign_in')

However this (on it's own) just forgets about the page the user wanted to visit initially, which confines usability.

Additional (controller) logic is required for more elegant handling.

UPDATE: correct redirect

Within the function, this holds the initial URL the user intended to go to.

By calling window.location.replace(this) (instead of explicitly redirecting to the sign in page), the app will try to redirect the user to the initially intended destination.

Although still impossible (unauthorized), this will now be a GET call (instead of JS/AJAX). Therefore Devise is able to kick in and redirect the user to the sign in page.

From there on, Devise operates as usual, forwarding the user to the originally intended URL after successful sign in.


A version mixing event binding with location.reload():

$(function($) {
  $("#new-user")
    .bind("ajax:error", function(event, xhr, status, error) {
      if (xhr.status == 401) {  // probable Devise timeout
        alert(xhr.responseText);
        location.reload();      // reload whole page so Devise will redirect to signin
      }
    });
});

Testing with Devise 3.1.1, this does correctly set session["user_return_to"], so the user returns to the page after signing in again ().

I added the alert as a simple way to address the inelegant message issue discussed here: Session Timeout Message in RoR using Devise