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

我怕爱的太早我们不能终老 提交于 2019-12-03 05:38:42
padi

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

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

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 replaced jquery-ujs with a complete rewritten rails-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:

  1. Use Rails.fire function:

    nativeFormEl = $("#new_subscription")[0] // you need the native DOM element
    Rails.fire(nativeFormEl, 'submit')
    
  2. You could also programmatically call the Rails.handleRemote handler (the one that actually submits forms with 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's just a wrapper that uses more recent Web API methods i.e. creating a CustomEvent and dispatches it to the EventTarget via dispatchEvent.

Try to trigger the submit.rails event:

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

Try doing an Ajax request by yourself:

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

That way, you do a POST request with the form data and execute the response as a script.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!