Abhinav
Abhinav

Reputation: 81

Rails 3: Form getting submitted twice

I am developing a Rails application that has forms generated using formtastic. I am developing & testing locally - that is - on localhost:3000 w/ Ruby-1.9.2, Rails-3.0.1, jQuery and AJAX.

Below is a sample screen output of the problem I am seeing. My forms are getting submitted twice within 1 second of each other. I can't understand why this is happening. I see this issue w/ all requests - including GET.

  1. Started POST "/businesses/6/edit_balance" for 127.0.0.1 at 2011-01-07 02:31:47 +0530 Processing by BusinessesController#edit_balance as JS Parameters: {"utf8"=>"✓", "authenticity_token"=>"zcWH08sV8kPbAYy7JQX64Cu2e1i/kEB1AB4x5a08CO8="

  2. Started POST "/businesses/6/edit_balance" for 127.0.0.1 at 2011-01-07 02:31:48 +0530 Processing by BusinessesController#edit_balance as JS Parameters: {"utf8"=>"✓", "authenticity_token"=>"zcWH08sV8kPbAYy7JQX64Cu2e1i/kEB1AB4x5a08CO8="

And so I am wondering whether I am making a basic programming error. If yes, then could you please suggest some solutions that I could try.

Upvotes: 8

Views: 3424

Answers (3)

Amir Rubin
Amir Rubin

Reputation: 860

I had this same problem right after deploying to Heroku... I pre-compiled my assets, and all of a sudden I was getting double AJAX submissions. I guess I somehow ended up with duplicate javascript files in public/assets.

To fix the problem I just deleted my entire public/assets directory.

Upvotes: 9

Abhinav
Abhinav

Reputation: 21

Thanks PolarBlau.. Let me try your suggestion..

Apnediving: Below are the bits of code that 1. create the form (form partial) 2. define the dialog that houses the form (dialog partial) and 3. the JS that attaches an action to the form.

Form Partial (credits_form)

- f.inputs :name => 'Edit Credits' do 
  = f.input :numeric_input_1, :label => 'Amount', :as => :select, :collection => [1000,2000,3000] 
  = f.input :boolean_input_1, :label => 'Add Credits'
  = f.commit_button :label => 'Submit' 

Dialog Partial

#edit-credits-dialog

- @user_input = UserInput.new

 = semantic_form_for @user_input, :remote => true do |f|     
 = render :partial => 'businesses/credit_form', :locals => {:f => f}

JS Code

$.getJSON('/businesses/' + id + '/load_credits', function(data) { 
    var form = $('#edit-credits-dialog form') ; 

    form.attr('action', '/businesses/' + id + '/edit_balance') ; <-- seems to be happening twice
    $('#edit-credits-dialog').dialog('open') ; <--- happens once 
}) ; 

Upvotes: 0

polarblau
polarblau

Reputation: 17744

If you're submitting the form with Javascript, try to set the submit button to be disabled when the form is submitted. With jQuery it would be something like this (not tested):

$('form').submit(function(){
  $(this).find(input[type='submit']).attr("disabled", "true");
  ... // submit form via AJAX
  return false;
});

Upvotes: 1

Related Questions