Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

submit a rails remote form with javascript

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?

like image 818
Matthew Avatar asked Dec 20 '11 04:12

Matthew


People also ask

What is submit () in JavaScript?

The submit() method submits the form (same as clicking the Submit button). Tip: Use the reset() method to reset the form.

Can you use JavaScript with Ruby on Rails?

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.

Which method is used to submit forms in JavaScript?

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".

What is remote form submission in rails?

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 *


2 Answers

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.

like image 101
mltsy Avatar answered Sep 21 '22 21:09

mltsy


This is simply in Rails way :

 $("#myform").trigger('submit.rails'); 
like image 41
Gopal S Rathore Avatar answered Sep 19 '22 21:09

Gopal S Rathore