Ajax redirection


#1

Hi,

Is there a simple way to redirect towards another page (controller,
action)
when using form_remote_tag ?

I used it tipically to check fields of a account login form. I’d like
if the user
exists, he’s redirected towards another page, otherwise I display some
error div’s.

Any ideas ?
Thanks a lot.
Seb


#2

You should put a callback in your tag like:

:complete => “redirect(request)”

and then add redirect() javascript function that will check
request.ResponseText and do a client-side redirect if it meets
required criteria

more on ajax callbacks here:
http://api.rubyonrails.com/classes/ActionView/Helpers/JavaScriptHelper.html#M000433


#3

if you are using rjs (plugin for 1.0 or built-in for 1.1), you can use
page.redirect_to

example:

/app/views/account/_login_form.rhtml

<%= form_remote_tag :url => { :action => :login } %>

<%= end_form_tag %>

/app/controllers/account_controller.rb

class AccountController < ApplicationController
def login
# the prototype library sends a “X-Requested-With” header containing
“XMLHttpRequest”
# so we can tell if it’s an AJAX call or not
if request.xhr?
# authenticate the user
@authenticated = User.authenticate(@params[:login],
@params[:password])
# go on to render the login.rjs template
else
# not an ajax call, so we display the login form partial instead
render :partial => “login_form”, :layout => false
end
end
end

/app/views/account/login.rjs

if @authenticated

user has authenticated so send them to where they need to go

page.redirect_to("/controller/action")
else

auth failed so update the message div to let them know

page.replace_html(“login_msg”, “Bad username or password”)
end