Rails jQuery UJS callbacks not triggering
Asked Answered
I

1

6

I'm attempting to trigger the ajax:success callback for a remote link. I'm on Rails 3.0.8 and jquery-rails 1.0.11. I ran the jquery generator to install the javascripts. Both jquery and jquery_ujs are included in my defaults and I can verify they are being included on the page.

Here's my javascript:

jQuery(function($) {
  $("#deactivate")
    .bind("ajax:success", function() {
      alert("HELLO");
    })
    .bind("ajax:error", function() {
      alert("GOODBYE");
    }
  );
});

The link:

= link_to 'Deactivate', activate_patient_path(patient), :id => 'deactivate', :class => "button button-red", :remote => true

The activate action:

def activate
    patient = Patient.find(params[:id])
    patient.do_not_call = !patient.do_not_call
    if patient.save
      render :nothing => true
    else
      render :status => 500, :nothing => true
    end
end

The ajax call seems to be working fine. The action is triggered and I can see the changes in the database. However, the ajax callbacks are not being triggered. I can't get any of them to work. I can get other events, such as click, to work perfectly.

If I debug rails_ujs in Firebug I see that the following code gets ran from the Rails ajax block:

success: function(data, status, xhr) {
  element.trigger('ajax:success', [data, status, xhr]);
}

I'm stumped. Any ideas?

Infract answered 20/6, 2011 at 1:1 Comment(2)
If I execute element = $("#activate"); element.trigger('ajax:success'); in the console I can get the callback to trigger. For some reason it just doesn't work with UJS.Infract
Using Firebug, if I put a breakpoint at the element.trigger('ajax:success', [data, status, xhr]) line in rails_ujs and then bind $("#deactivate") to ajax:success when stopped the callback will trigger. The callback will continue to trigger correctly when I click the link until I refresh the page. It seems that $("#deactivate") is not the same reference to the element that the trigger is being executed upon.Infract
C
12

make sure that you are not including jquery.js again after rails.js...I ran into a similar problem where jquery.js was included twice, and rails.js was included in between.

Calyptrogen answered 29/6, 2011 at 9:59 Comment(1)
That was it. jQuery Tools was embedding an older version of jQuery.Infract

© 2022 - 2024 — McMap. All rights reserved.