Question

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.

Console output

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'
Was it helpful?

Solution

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

OTHER TIPS

May be you have jquery_ujs twice in your application or in your JavaScript folder.

Make sure that should not be loaded twice try to check by page source.

I know it, it's 100% issues regarding that js related.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top