Tjerk Dijkstra
Tjerk Dijkstra

Reputation: 35

Rails close fancybox on ajax request

I've been trying lots of stuff and I can't get my head around this problem. First off all I have a form partial inside a fancybox.

this is : *_form.html.erb*

 <%= form_tag sessions_path , remote:true , id: "login_form" do %>
 <div class="field">
  <%= label_tag :email %>
  <%= text_field_tag :email, params[:email] %>
 </div>
 <div class="field">
  <%= label_tag :password %>
  <%= password_field_tag :password %>
 </div>
  <div class="actions"><%= submit_tag "Inloggen" %></div>
 <% end %>

I post the data inside this form with a jQuery function from my application.js

jQuery('#login_button').fancybox({
  type: 'ajax'
})


jQuery('#login_form').submit(function() {  
    var data = jQuery(this).serialize();

        $.getJSON('sessions/new.js?callback=?&variable=loginData', { 
        loginData: data 
        }, function(data) {

            if(data == 0){
                alert('Your account is not activated yet');
            }
            if(data == 1){
                alert('Password incorrect');
            }
            // login correct
            if(data == 2){
                 //$.fancybox.close();
                 window.parent.jQuery.fn.fancybox.close();
            } 
        });

    return false;
});

The problem is that I get no feedback when Iam in the fancybox. If I check the console for XHR request, it sends the data and I get the appropriate response but the fancybox doesn't close and I do not get any alerts.

Last but not least my sessions controller

  def create
@user = User.find_by_email(params[:email])

#if there is a user with that e-mail, is it activated?
if @user
  if @user.user_level != '1' 
    @response = 1
  end
end

#check the login information with has_secure_password, user has to be activated
if @user && @user.authenticate(params[:password]) && @user.user_level == '1'
  session[:user_id] = @user.id
  @response = 2
else
  @response = 0
end

respond_to do |format|
  format.json { render :json => @response }
end

How do I close the fancybox if the response is equal to 2? And how I can I show the user that their input is incorrect from inside the fancybox?

Upvotes: 1

Views: 642

Answers (1)

Valery Kvon
Valery Kvon

Reputation: 4496

respond_to do |format|
  format.js do
    if @response == 2
      render :js => "$('#fancybox-content').remove();"
    end
  end
end

Or create create.js.erb:

# controller
respond_to do |format|
  format.js { }
end

# create.js.erb

<% if @response == 2 %>
  $('#fancybox-content').remove();
<% end %>

This is a basic approach. Extend your code if you want another behavior when create failed.

Upvotes: 1

Related Questions