3

I have a simple scenario where I want to request a page. The request format is AJAX. If there is some error in the controller/action logic for that request, I want to redirect to an error page. The issue is that a redirect is not a JavaScript response type, so I am not sure whether it will work.

If there are no errors, then I want the page to be updated via the appropriate JavaScript response type.

What is best practice to achieve redirect responses given that the request format is AJAX?

halfer
  • 19,824
  • 17
  • 99
  • 186
deruse
  • 2,851
  • 7
  • 40
  • 60
  • can you specific the ajax library that you use? jquery or prototype-js etc – Jirapong Jan 10 '12 at 04:20
  • this will help you http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call – dbKooper Jan 10 '12 at 06:44
  • I suspect that, based on Stack Overflow's current on-topic rules, this is rather broad, and it may be put on hold. – halfer Aug 08 '18 at 13:12

3 Answers3

3

This blog post enlightened me on what I think is the right way to do this, if your ajax response is ajax; at least, in the unobtrusive javascript paradigm. In essense, the ajax call always returns a standard json package, which can be parsed for information payload or a redirect url.

DGM
  • 26,629
  • 7
  • 58
  • 79
3

You can also put this in your ApplicationController to redirect properly for AJAX requests:

class ApplicationController < ActionController::Base

  # Allows redirecting for AJAX calls as well as normal calls
  def redirect_to(options = {}, response_status = {})
    if request.xhr?
      render(:update) {|page| page.redirect_to(options)}
    else
      super(options, response_status)
    end
  end

end
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
  • @iWasRobbed- I like this answer, but the OP specifies Rails 3, and so `render(:update)` won't work unless I'm mistaken – Yarin Aug 25 '13 at 23:05
  • @Yarin Works just fine for Rails 3. It's when you get into Rails 3.1+ that you need to replace `render(:update)` – iwasrobbed Aug 26 '13 at 13:50
1

If you use jQuery, you can use .ajaxError()

$(document).ajaxError(function(event, request, settings){
  location.href = '/error.html';
});

or assume you do a ajax post

var jqxhr = $.post("example.php", function() {
  // Do what it completed will do
})
.error(function() { 
  location.href = '/error.html';
})
Jirapong
  • 24,074
  • 10
  • 54
  • 72