multiple submits with ajax & submit

I think I have this boiled down to:

assets has a .js

jQuery.ajaxSetup({

'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}

})

$(document).ready(function() {

$("#new_user").submit(function(){

	$.post($(this).attr("actions"), $(this).serialize(), null, "script");

	return "false";

})

})

form view has

<%= submit_tag “Add User” %>

What’s happening is that the request is being processed twice and failing on the second because of model validations:

Started POST “/users” for 127.0.0.1 at 2012-01-16 15:27:39 -0500

Processing by UsersController#create as JS

Parameters: {“utf8”=>“✓”, “authenticity_token”=>“mkw9MRu9jeCQuT13B3iG/nxL3iBKvMLg+6I5YZUKZJg=”, “user”=>{“email”=>“sadf”, “password”=>"[FILTERED]"}}

(0.0ms) SELECT 1 FROM “users” WHERE “users”.“email” = ‘sadf’ LIMIT 1

SQL (29.1ms) INSERT INTO “users” (“active”, “created_at”, “email”, “password”, “updated_at”) VALUES (?, ?, ?, ?, ?) [[“active”, true], [“created_at”, Mon, 16 Jan 2012 20:27:39 UTC +00:00], [“email”, “sadf”], [“password”, “asdfsa”], [“updated_at”, Mon, 16 Jan 2012 20:27:39 UTC +00:00]]

Rendered users/create.js.erb (0.3ms)

Completed 200 OK in 176ms (Views: 30.4ms | ActiveRecord: 29.4ms)

Started POST “/users” for 127.0.0.1 at 2012-01-16 15:27:39 -0500

Processing by UsersController#create as HTML

Parameters: {“utf8”=>“✓”, “authenticity_token”=>“mkw9MRu9jeCQuT13B3iG/nxL3iBKvMLg+6I5YZUKZJg=”, “user”=>{“email”=>“sadf”, “password”=>"[FILTERED]"}, “commit”=>“Add User”}

(0.0ms) SELECT 1 FROM “users” WHERE “users”.“email” = ‘sadf’ LIMIT 1

Completed 422 Unprocessable Entity in 6ms

ActiveRecord::RecordInvalid (Validation failed: Email has already been taken):

app/controllers/users_controller.rb:44:in `create’

QUESTION:

How do I not do the html submit but keep the ajax submit?

are you not using remote: true ??

Then you can also put a disable_with: which only allows the button to be pressed once.

Rails 3.1.3

Here is a line from my view that was made with the agile web development book:

<%= button_to 'Add to Order', line_items_path(item_id: item), remote: true, disable_with: 'Adding...' %>

jordan

are you not using remote: true ??

:remote => true should be set within form_tag

tom

Changed to:

<%= form_for(@user, :id=>‘new_user’, :remote=>true) do |f| %>

Now it’s submitting twice via .js… Progress!

and now change 'return "false"' to 'return false' inside your jquery submit()

tom

Thanks Tom.

I feel like anyone doing this for the first time: clumsy!