Rails 3 application not redirected after submitting an AJAX form

I have an Authlogic c login form :remote => truethat does a little inline validation using an RJS template if the user / password is invalid. This works fine, but when the credentials are valid, they are not redirected properly elsewhere.

Here is the controller that responds to form input:

class UserSessionsController < ApplicationController
  respond_to :html, :js

  before_filter :require_no_user, :only => [:new, :create]
  before_filter :require_user, :only => :destroy

  def new
    @user_session = UserSession.new
  end

  def create
    @user_session = UserSession.new(params[:user_session])

    respond_to do |format|
      if @user_session.save     
        flash[:notice] = "Login successful!"
        format.html { redirect_to account_url }
      else
        format.js
      end
    end
  end

  def destroy
    current_user_session.destroy
    flash[:notice] = "Logout successful!"
    redirect_to root_path
  end

end

The part works format.js, but if the user / password is good ( format.html), nothing happens. However, if I look at the development.log file, it requests the account_url page. It just does not redirect you to the browser. I think it returns the account page via AJAX, and I just want a normal redirect.

HTML for the form:

<%= simple_form_for(
:user_session, @user_session, 
:url => { :controller => 'user_sessions', :action => "create" },
:html => { :id => 'login-dropdown' }, :remote => true) do |f| %>
+3
3

. Per http://www.ruby-forum.com/topic/168406#945053, :

def redirect_to(options = {}, response_status = {})
  if request.xhr?
    render(:update) {|page| page.redirect_to(options)}
  else
    super(options, response_status)
  end
end

xhr. "" , .

+8

, :

allpication.js

$(document).ready(function(){
    $(document).ajaxError( function(e, xhr, options){
    if("401" == xhr.responseText)
    {
       $(location).attr('href','/users/sign_in');
    }
  });
}) 

:

respond_to do |format|
    format.html {redirect_to @new_user_session_url}
    format.js { render :text=>'401' ,:status=>401}
end

, ....

0
app
 views
   user_sessions
     create.js.erb(create file this)

in your action add this code

 def create
  @user_session = UserSession.new(params[:user_session])

respond_to do |format|
  if @user_session.save     
    flash[:notice] = "Login successful!"
    @url = account_url
  end
 format.js
end

end

in your create.js.erb

window.location.replace(<%= @url %>);
0
source

Source: https://habr.com/ru/post/1794233/


All Articles