Rails Against The Machine

Just a mind dump. Why are you even reading this?

Wednesday, 21 January 2009

 

redirect posts using javascript

Lets say need authentication on a form submit.
We want the post to go through as normal if the user is logged on. If the user is not logged on the authentication system should intercept the request and show the login form. If they successfully login they should be redirected to the origional request.

Naively you would suppose this would be easy. You simply store the origional request in the session (session[:stored_location] = request.env['REQUEST_URI']) then redirect to that location if the login action is successfull. The problem with this is you can't redirect to a non-GET request.

You can however do any request you like with javascript. So we steal the following function from

    postwith: function(to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}


http://mentaljetsam.wordpress.com/2008/06/02/using-javascript-to-post-data-between-pages/

which can be called by an rjs template in response to an ajax request by the login form.

<div id="login_div">
<%= error_messages_for :user, :header_message => "Custom message one", :message => "Custom message two" %>
<% remote_form_for :user, :url => session_path do |f| -%>
<div>
<p><label for="email">Email</label><br/>
<%= f.text_field :email, :required => true %></p>

<p><label for="password">Password</label><br/>
<%= f.password_field :password, :required => true %></p>
<%= submit_tag 'Submit' %>
</div>

<% end -%>
</div>


so if login fails we use rjs to replace the div

page.replace_html 'login_div',{:partial=>'login', :object=>@user}
page.visual_effect :highlight, "login_div", :duration=>2


if it succeeds we call the post function

page<<"Global.postwith('#{page_url}',#{params.to_json})"

Archives

July 2007   August 2007   September 2007   December 2007   January 2008   February 2008   March 2008   April 2008   June 2008   July 2008   August 2008   October 2008   November 2008   January 2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]