jquery-ujs ajax events are not handled

1.5k views Asked by At

I'm trying to implement ajaxy signup with rails 3. I'm using jquery-ujs and remote form. I access the signup form with $.get request, and it is displayed correctly. This signup form is remote:

form_for @user, :remote => true, :html => {"data-type" => "html"} do |f|

In my application.js, if the ajax request for getting the form is successful, I'm trying to bind handler for ajax events from unobtrusive javascript:

var load_remote_form = function(evt) {
    var href = $(this).attr('href'); 
    // load form template
    $.get(href, {}, function(data) {
        $('body').append(data);

        $('form[data-remote]').bind("ajax:beforeSend", function(e) {
            console.log("Caught beforeSend!");
        });
    });
    evt.preventDefault();
};

$(document).ready(function() {
    $('a#signup').click(load_remote_form);   
});

Chrome's development tools show that the event "ajax:beforeSend" is binded, but it is never handled (I have nothing in the javascript console when I send the form, though in rails log I see that the request is processed correctly and the response is send). I can bind other events to the same selector (form[data-remote]), like click, and they are handled correctly.

Ajax events binded through .live are not handled as well. But if the form is rendered as part of the layout (i.e. it is on stand-alone page like http://localhost:3000/signup/), binded "ajax:beforeSend" is handled correctly.

My controller (just for a case, it may be badly written, but I'm pretty sure it works):

class UsersController < ApplicationController

  layout :layout_for_type

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      session[:user_id] = @user.id
      flash[:notice] = "You have successfully registered."
      redirect_to root_url
    else
      if request.xhr?
        render :action => 'new', :status => :unprocessable_entry, :layout => false
      else
        render :action => 'new'
      end
    end
  end

  def layout_for_type
   request.xhr? ? nil : "application"
  end

end

What am I doing wrong? May be there is a better approach for implementing such "double-ajaxed" forms?

1

There are 1 answers

0
Paul Nossoff On BEST ANSWER

Silly me. I've completely overlooked another potential source of problems. I had

javascript_include_tag :all

in my application layout, and that caused including both jquery.js and jquery.min.js into my page. It turned out to be the cause of that strange behavior. Removing jquery.min.js did the trick. Hope that might be useful for someone someday.