开发者

Rails: JS Controller Being Called Twice for Some Reason

For some reason when I click on a button, my controller and the resulting jquery function gets called twice. Since the js function being called is toggle, this is a problem as it causes the code to jump in and out of view.

Here is the form:

Unseen Notifications: <%=  current_user.notification_unseen %> </div>
                <%= button_to "show", {:action => "seen", :controller=>"notifications"}, :remote => true %>

Here is the controller:

def seen
    respond_to do |format|
      format.js 
    end
  end

Here is the jquery:

$("div#notifications").toggle();
$("div#count").html("<%= escape_javascript( render :partial => 'notifications/count')%>");

I am at a loss for why on earth this would pos开发者_Go百科sibly happen. I have been very careful not to double click and don't know how to prevent it. Any suggestions would be greatly appreicated.


I had a recent problem like this before, when I had 2 jquery libraries included. In particular, check that you only have jquery_ujs.js and not jquery.js. Seems like when you include both of them certain js functions are called twice.

Hope this helps!


If Benjamin's suggestion doesn't work, you could go with cheats and hacks and add 1 to some global var on each click (which would happen twice), then use modulus to only trigger your action when (global_counter % 2 == 0).

Just to be clear, this is a terrible solution that you should avoid using if at all possible...


I'm new to rails and had the same problem. It turns out I had:

<%= javascript_include_tag "application" %>

In both my view and in application.html.erb. I removed one of them and voila, fixed.


If you're running jquery in rails 5.1 and beyond, as rails dropped jquery support and switch to its own ujs, you need to remove //= require rails-ujs from application.js file.

I had the same problem while running latest version of rails, this solved my problems.


Similar to Michael Mayer's and Benjamin Tan Wei Hao's answers:

it is possible for a second <%= javascript_pack_tag 'application' %> to get added to the layout (even automatically) when implementing Webpacker. This happened recently, when modernizing an older application that isn't quite ready for Rails 7.

TL;DR;

Beware the second application.js reference.


Taking the jquery_ujs.js worked for me.

Take a close look at the file application.html.erb to see if that is referring to jquery.js and jquery_ujs.js. If so, just take the jquery_ujs.js out, refresh the browser and try it again.

Also, take a look at the page source and see if jquery_ujs and jquery is referred to at the same time. If so, search in the source files for references to that jquery_ujs.

Worked for me, thanks guys.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜