[ACCEPTED]-Rails 3: How to "redirect_to" in Ajax call?-redirect

Accepted answer
Score: 103

Finally, I just replaced

redirect_to(:controller => 'jobs', :action => 'index')

with this:

render :js => "window.location = '/jobs/index'"

and it 1 works fine!

Score: 71

There is very easy way to keep the flash 5 for the next request. In your controller 4 do something like

flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"

The flash.keep will make sure the 3 flash is kept for the next request. So when 2 the root_path is rendered, it will show the given 1 flash message. Rails is awesome :)

Score: 29

I think this is slightly nicer:

render js: "window.location.pathname='#{jobs_path}'"

0

Score: 26

In one of my apps, i use JSON to carry on 3 the redirect and flash message data. It 2 would look something like this:

class AccessController < ApplicationController
  ...
  def attempt_login
    ...
    if authorized_user
      if request.xhr?
        render :json => {
          :location => url_for(:controller => 'jobs', :action => 'index'),
          :flash => {:notice => "Hello #{authorized_user.name}."}
        }
      else
        redirect_to(:controller => 'jobs', :action => 'index')
      end
    else
      # Render login screen with 422 error code
      render :login, :status => :unprocessable_entity
    end
  end
end

And simple 1 jQuery example would be:

$.ajax({
  ...
  type: 'json',
  success: functon(data) {
    data = $.parseJSON(data);
    if (data.location) {
      window.location.href = data.location;
    }
    if (data.flash && data.flash.notice) {
      // Maybe display flash message, etc.
    }
  },
  error: function() {
    // If login fails, sending 422 error code sends you here.
  }
})
Score: 20

Combining the best of all answers:

...
if request.xhr?
  flash[:notice] = "Hello #{authorized_user.name}."
  flash.keep(:notice) # Keep flash notice around for the redirect.
  render :js => "window.location = #{jobs_path.to_json}"
else
...

0

Score: 0
def redirect_to(options = {}, response_status = {})
  super(options, response_status)
  if request.xhr?
    # empty to prevent render duplication exception
    self.status = nil
    self.response_body = nil
    path = location
    self.location = nil

    render :js => "window.location = #{path.to_json}"
  end
end

0

Score: 0

I didn't want to modify my controller actions 1 so I came up with this hack:

class ApplicationController < ActionController::Base
  def redirect_to options = {}, response_status = {}
    super

    if request.xhr?
      self.status        = 200
      self.response_body = "<html><body><script>window.location.replace('#{location}')</script></body></html>"
    end
  end
end

More Related questions