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?
The submit() method submits the form (same as clicking the Submit button). Tip: Use the reset() method to reset the form.
While RoR is a server side web development framework, JavaScript is a client side programming language. Therefore, you can easily use both of them within a single tech stack.
The formmethod attribute defines the HTTP method for sending form-data to the action URL. The formmethod attribute overrides the method attribute of the <form> element. The formmethod attribute is only used for buttons with type="submit".
Remote form submission in Rails In the example below, we will first create a simple form to get the user data and when the form is submitted we will save the user data and in response render a partial displaying the user information without reloading the page. *Submitting a form using AJAX *
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.
This is simply in Rails way :
$("#myform").trigger('submit.rails');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With