Search code examples
jqueryajaxruby-on-rails-3ujs

How to asynchronously submit a form when clicking a control, Ajax-style?


In a Rails3 app, I have a boolean attribute root represented by a radio control (not checkbox) and I want to be able to automatically save the new value of root - Ajax-style.

<%= form_tag(set_root_project_page_path(@project, page), :remote => true, :method => :put ) do -%>
  <%= radio_button_tag('root', page.id, page.root?, :onclick => "this.form.submit();") %>
  <%= submit_tag 'set root', :disable_with => 'wait...' %>
<% end -%>

I currently have 2 submit options:

  1. the submit_tag works as expected: the action is called through an XHR, and my set_root.js.erb template updates the page accordingly, but I don't want to have to click a separate button for that, so then I tried:
  2. adding :onclick => "this.form.submit();" to my radio control. This submits the form, but in a classical, non-ajax way, so I get an error for missing the html template.

What should I do to have my form submitted asynchronously when clicking the radio control, (maybe an UJS approach)?

Note: I'm using jQuery in my project.


Solution

  • try :onclick => "$(this.form).trigger('submit.rails')