Redirecting AJAX requests in Rails

AuthorMáximo Mussini
·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 😃

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.

Axios

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

axios.interceptors.response.use(
  response => {
    if (response.status === AJAX_REDIRECT_STATUS_CODE) {
      window.location = response.headers.location
    }
    return response
  },
  error => Promise.reject(error),
)