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