With Rails UJS, how to submit a remote form from a function

I am using Rails UJS. I have a form to do remote submit as follows:

<form accept-charset="UTF-8" action="/subscriptions" class="new_subscription form-horizontal" id="new_subscription" data-remote="true" data-type="json" method="POST"> 

I am trying to find a way to submit this form from a JavaScript function. I tried:

 var form$ = $("#new_subscription"); form$.get(0).submit(); 

but the problem is that it submits the form without the remote, it submits to the server and refreshes the page. Any idea why this is? Is there a way to submit a remote form?

thanks

+8
jquery ruby-on-rails ruby-on-rails-3 ujs
source share
3 answers

Perhaps for those who use jquery-ujs (Rails 5.0 by default and below), as Mikhail said, as already answered, triggering a custom jquery event will work, that is:

 $("#new_subscription").trigger("submit.rails"); 

For those who stumbled upon this question in 2017 and using Rails 5.1, the answer will be different. Rails 5.1 dropped jquery as a dependency and therefore replaced jquery-ujs with a complete rewrite of rails-ujs . See: http://weblog.rubyonrails.org/2017/4/27/Rails-5-1-final/

Thus, you must call the correct CustomEvent object in rails-ujs:

There is currently no published / recommended way to do this in the documentation (aka RailsGuides), but here are a few options that you can use just by looking at the Rails source code:

  • Use the Rails.fire function:

     nativeFormEl = $("#new_subscription")[0] // you need the native DOM element Rails.fire(nativeFormEl, 'submit') 
  • You can also programmatically call the Rails.handleRemote handler (the one that actually submits forms using data-remote=true via XHR:

     nativeFormEl = $("#new_subscription")[0] // you need the native DOM element Rails.handleRemote.call(nativeFormEl, event); // unfortunately, you cannot reference the previously created submit CustomEvent object by rails-ujs.js // ... or ... Rails.handleRemote.call(nativeFormEl) // submits via XHR successfully, but throws an error after success callback at Rails.stopPropagation 

I prefer option 1 because it is just a shell that uses more modern web API methods, i.e. creates a CustomEvent and dispatches it to an EventTarget via dispatchEvent .

+16
source share

Try to fire the submit.rails event:

 $("#new_subscription").trigger("submit.rails"); 
+14
source share

Try the Ajax request yourself:

 $('#new_suscription').submit(function(){ /*do whatever you want here*/ $.post('/subscriptions',$(this).serialize(),function(){},'script'); } 

This way you execute a POST request with the form data and execute the response as a script.

0
source share

All Articles