6

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 possibly happen. I have been very careful not to double click and don't know how to prevent it. Any suggestions would be greatly appreicated.

Spencer
  • 21,348
  • 34
  • 85
  • 121

6 Answers6

17

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!

Benjamin Tan Wei Hao
  • 9,621
  • 3
  • 30
  • 56
5

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...

ElonU Webdev
  • 2,451
  • 14
  • 15
4

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.

1

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.

Melih Alan
  • 79
  • 1
  • 9
1

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.

SMAG
  • 652
  • 6
  • 12
0

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.

mrk
  • 4,999
  • 3
  • 27
  • 42