Redirecting AJAX requests in Rails

January 11, 2016 2 min read

jquery-rails powers links and forms in Rails: it’s what makes remote: true work, allowing any link to make an AJAX request unobtrusively.

rails-ajax_redirect is an extension to this unobtrusive behaviour that adds AJAX support to redirect_to. It allows us to redirect an AJAX request as usual, instead of having to perform the redirect by handling the response manually in JS every time.

This is helpful in many different scenarios, and just like remote: true, it allows us to skip some of the boilerplate in cases where we need to redirect the user to a different page.

Rails::AjaxRedirect extends redirect_to to use a custom status code for ajax requests, while still setting the Location header. On the front-end, it adds a handler for the ajax:success event, that navigates to the location in the header for responses that have the custom status code.

This makes it possible to write a simple redirect as usual, but without having to handle it manually every time :smiley:

If your application uses Turbolinks check out turbolinks-redirect, on which rails-ajax_redirect is based on. The advantage is that it will perform faster navigation by leveraging Turbolinks to visit the new location.

AngularJS

If your application makes the AJAX request using $http instead of jQuery, it will be necessary to add an interceptor similar to this:

app.config ($httpProvider) ->
  $httpProvider.interceptors.push 'AjaxRedirectInterceptor'

  # Add a header to let Rails know that it's an Ajax request.
  $httpProvider.defaults.headers.common['X-REQUESTED-WITH'] = 'XMLHttpRequest'

app.service 'AjaxRedirectInterceptor', ($window, $location, $q) ->
  interceptor =
    response: (response) ->
      if response.status is AJAX_REDIRECT_STATUS_CODE
        $window.location = response.headers().location
        $q.reject(response)
      else
        response
By @Maximo @MaximoMussini