submit a rails remote form with javascript

Matthew picture Matthew · Dec 20, 2011 · Viewed 30k times · Source

In my rails app I have a remote form that looks something like this for example:

<%= form_tag some_path, :method => :get, :id => 'my-form', :remote => true do %>
  <%= text_field_tag :search, params[:search], :id => 'search-field' %>
  <%= submit_tag 'Go' %>
<% end %>

Now i would like to submit this form via javascript and trigger all rails remote form callbacks. So far i have tried a few things but nothing seems to be working.

Things i have tried:

$('#my-form').trigger('onsubmit')

$.rails.callFormSubmitBindings( $('#search-form') )

but no luck so far. Any ideas?

Answer

mltsy picture mltsy · Oct 4, 2017

In Rails 5.1+, which replaces the old jquery-ujs with a non-jquery rails-ujs, the above answers no longer work, always submitting the form via an HTML HTTP request. This is how you trigger the new rails submit event handler:

var elem = document.getElementById('myform') // or $('#myform')[0] with jQuery
Rails.fire(elem, 'submit');

(Can't tell you how long it took me to figure that one out...) For some reason, the regular events don't bubble up properly to the delegated event handler attached by rails using rails' new delegate function, when they are triggered by jQuery.