Rails: JS controller invoked twice for some reason

For some reason, when I click the button, my controller and the resulting jquery function are called twice. Since the js function being called is switched, this is a problem, as it causes the code to be scanned and turned off.

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 jQuery:

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

I am at a loss why this might happen. I tried very hard not to double-click and do not know how to prevent it. Any suggestions would be very helpful.

+6
javascript jquery ruby ajax ruby-on-rails
source share
5 answers

I had as recent a problem as before when I had 2 jquery libraries. In particular, make sure that you only have jquery_ujs.js, not jquery.js. It appears that when you include both of them, some js functions are called twice.

Hope this helps!

+15
source share

If Benjamin's suggestion does not work, you can go with cheats and hacks and add 1 to some global var for each click (which happens twice), and then use the module only to trigger your action when (global_counter% 2 == 0).

Just to be clear, this is a terrible decision that you should avoid if possible ...

+5
source share

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

<%= javascript_include_tag "application" %>

Both in my view and in application.html.erb. I deleted one of them and voila, fixed.

+2
source share

Taking jquery_ujs.js worked for me.

Look carefully at the application.html.erb file to see if this applies to jquery.js and jquery_ujs.js. If so, just open jquery_ujs.js, refresh your browser and try again.

Also, look at the source of the page and see if jquery_ujs and jquery are specified at the same time. If so, search the source files for links to this jquery_ujs.

Worked for me, thanks guys.

0
source share

If you run jquery in rails 5.1 and later, because rails has dropped jquery support and switched to their own ujs, you need to remove // ​​= require rails-ujs from the application.js file.

I had the same problem when starting the latest version of rails, this solved my problems.

0
source share

All Articles