My Rails app is submitting two posts requests immediately one after the other. It only happens on forms I am manually submitting with jQuery.
If I navigate to another page, only one and try to submit the form again, only one request is submitted. When I navigate back, 3 requests get submitted. For each navigation forward, then back, one request is added.
Here's how I submit the form.
jQuery(document).on "ready page:change", ->
$('body').on 'click', '[data-behaviour="submit-on-check"]', ->
$(@).closest('form').submit()
Here is the form:
= form_for task, url: complete_task_path(task) , remote: true do |f|
= f.check_box :complete, class: 'complete', data: { behaviour: 'submit-on-check' }
My manifest.
//= require jquery
//= require jquery.ui.effect-highlight
//= require jquery_ujs
//= require turbolinks
//= require_tree .
My Gemfile (Rails 4.0.2):
gem 'jquery-rails'
gem 'turbolinks'
gem 'jquery-ui-rails'
As you're using Turbolinks, the page instance does not change when you navigate from a page to another. I guess as a result, each time the page:change
event is fired you bind a new handler/closure using $('body').on
. As the previous handlers remain bound to the DOM, multiple instances of your closure are executed.
You may try to unbind the event before applying it again, or use a variable in the appropriate closure scope to ensure the handler is only applied once.
bound = false
jQuery(document).on "ready page:change", ->
unless bound
$('body').on 'click', '[data-behaviour="submit-on-check"]', ->
$(@).closest('form').submit()
bound = true