I'm using Rails UJS. I have a form setup to do a remote submit like so:
<form accept-charset="UTF-8" action="/subscriptions" class="new_subscription form-horizontal" id="new_subscription" data-remote="true" data-type="json" method="POST">
I'm trying to find a way to submit this form from a JavaScript function. I've tried:
var form$ = $("#new_subscription");
form$.get(0).submit();
but the problem with this is that it submits the form w/o the remote, it posts to the server and refreshes the page. Any idea why that is? Is there a different way to submit a remote form?
Thanks
Try doing an Ajax request by yourself:
That way, you do a POST request with the form data and execute the response as a script.
Perhaps for those using
jquery-ujs
(Rails 5.0 default and below), as Mikhail as already answered, triggering the custom jquery event will work, i.e.:For those who have stumbled upon this question in 2017 and is using Rails 5.1, the answer will be different. Rails 5.1 has dropped
jquery
as a dependency and therefore has replacedjquery-ujs
with a complete rewrittenrails-ujs
. See: http://weblog.rubyonrails.org/2017/4/27/Rails-5-1-final/As such, you'll have to trigger the proper CustomEvent object in rails-ujs:
As of the moment, there's no published/recommended way of doing it in the documentation (a.k.a. RailsGuides), but here are a number of options that you could use just by looking at Rails' source code:
Use
Rails.fire
function:You could also programmatically call the
Rails.handleRemote
handler (the one that actually submits forms withdata-remote=true
via XHR:I prefer Option 1 because it's just a wrapper that uses more recent Web API methods i.e. creating a
CustomEvent
and dispatches it to theEventTarget
viadispatchEvent
.Try to trigger the
submit.rails
event: