submit a rails remote form with javascript

ぃ、小莉子 提交于 2019-11-30 04:54:43

You can just use .submit();

$("#my-form").submit();

This is simply in Rails way :

 $("#myform").trigger('submit.rails');

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.

How about using rails_ujs and simply do the following:

Rails.fire(form, 'submit');

(where form is a DOM Element)

This feels like a proper Rails way to do it.

You can check out the source here – https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts/rails-ujs/utils/event.coffee#L34

How about passing json from controller and capturing it by your js.

Now, controller's action as

respond_to do |format|
      if some condition
        format.json { render :json => {:success => true} }
        format.html{ redirect_to some_path, :notice => "successfully created" }
      else
        ...
      end
end

And capturing the json in js as

$('#my-form').bind 'ajax:success', (event,data) ->
  if(data.success == true)
    ...

Not exactly what you are looking for but hope this turns out to be of any help.

@mltsy answer works perfect for me. However, wanted to reiterate that this requires the use of rails-ujs. If you've upgraded from an older version like me, you might still be using the jquery dependent jquery_ujs. If you're getting ReferenceError: Can't find variable: Rails in your console, check your application.js and make sure you have rails-ujs or @mltsy's great answer won't work. I wanted to leave a comment instead of an answer, but Stack won't let me.

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