submit a rails remote form with javascript
Asked Answered
F

9

41

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?

Frazzled answered 20/12, 2011 at 4:31 Comment(1)
What about $("#my-form").submit()? Does it fire the necessary callbacks? I know I've used similar in my own code.Amanda
M
-10

You can just use .submit();

$("#my-form").submit();
Mandi answered 20/12, 2011 at 4:35 Comment(3)
Just want to add that it must be called on a jQuery object. For example if you do something like $('.a').change(function { this.submit() }) it wont work. You must wrapp this in a jQuery object like $(this). Then you can call the sumbit on that.Locution
Warning : The form will NOT be submitted remotly (by ajax). Instead a full refresh will occurDamned
Can you please update or remove this misleading answer? Submitting a remote form in a non-remote way makes no sense. Gopal's answer is the correct.Rugen
A
95

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.

Anile answered 4/10, 2017 at 20:19 Comment(4)
I'm getting this error ReferenceError: Can't find variable: RailsAffluent
This answer is old but this is new info for me. Thanks bro.Kelleekelleher
To solve the error ReferenceError: Can't find variable: Rails, make sure you provide Rails as a plugin in environment.js: environment.plugins.prepend('Provide', new webpack.ProvidePlugin({ Rails: ['@rails/ujs'] }) ) Schwing
Thank you very much for this answer! @Affluent I'm experiencing the same issue. I found out that you can use jQuery.rails.fire (or $.rails.fire) in Rails 5.1+ and 5.2+. See here for the code on backwards compatibility.Dyke
S
81

This is simply in Rails way :

 $("#myform").trigger('submit.rails');
Surbase answered 6/4, 2013 at 5:13 Comment(3)
This is the real answer. It preserve the ajax submitting behavior of a remote form. Thanks !Damned
Mind the Comment of Ismael: You have to wrap your form in a jQuery object for remote submitting behaviour. So not myForm.submit(), but $(myForm).submit(). I didn't spot the issue for quite some time either...Hammering
This should be marked the correct answer in modern versions of RailsProstration
O
16

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

Odel answered 23/4, 2018 at 19:4 Comment(0)
D
8

If you don't have access to Rails from your javascript, and you don't want to try to get it set up, there is an easier solution!

You can use requestSubmit on the html element, instead of submit, and it will work the way you'd expect it to, since requestSubmit raises a submit even, and submit does not.

See the difference between submit and requestSubmit here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

In the case above, you could use:

$('#my-form')[0].requestSubmit()
Dilution answered 25/2, 2021 at 22:36 Comment(2)
This is a beauty. Wasn't even aware that requestSubmit was a thing and could be used to remotely submit the form. Thanks!Renal
Caveat to this that burned us: This isn't supported on Internet Explorer or Safari, at all. caniuse.com/mdn-api_htmlformelement_requestsubmitRenal
P
4

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.

Photoreconnaissance answered 20/12, 2011 at 6:8 Comment(2)
I believe he is simply asking how to submit the form itself.Mandi
wont the form be submitted remotely by itself to 'some_path' as stated.Fuse
A
4

I'm updatting the answer to rails 6.

If you are having this issue in rails 6, it is likelly that you forgot to add the parameter "format: :js" to the form builder.

<%= form_tag some_path, :method => :get, :id => 'my-form', :remote => true,
         :format => :js do %>
  <%= text_field_tag :search, params[:search], :id => 'search-field' %>
  <%= submit_tag 'Go' %>
<% end %>

You will also need to include a format.js in your controller.

def update
    respond_to do |format|
      if @model.update(user_params)
        format.html { redirect_to @model, notice: 'Model was successfully updated.' }
        format.json { render :show, status: :ok, location: @model }
        format.js {
          logger.debug "this will run in the update was ok."
        }
      else
        format.html { render :edit }
        format.json { render json: @model.errors, status: :unprocessable_entity }
        format.js {
          logger.debug "this will run in the update was not ok."
        }
      end
    end
  end

Now, from the JavaScript, you can just call the submit to this form regularly.

this.form.submit()
Adulate answered 16/12, 2019 at 13:9 Comment(0)
O
2

I know this is an old topic but I have been struggling with this now for some time and finally found a solution.

I had a form with remote: true that included a file_field and I wanted the form to submit automatically as soon as the user added the file. I tried onchange: form.submit(); but that way the form was submitted as HTML.

My solution: clicking the (hidden) form submit button with JS:

onchange: $("#submit-button").click();
Owner answered 13/3, 2020 at 15:45 Comment(0)
W
1

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

Wideopen answered 22/3, 2018 at 19:40 Comment(0)
M
-10

You can just use .submit();

$("#my-form").submit();
Mandi answered 20/12, 2011 at 4:35 Comment(3)
Just want to add that it must be called on a jQuery object. For example if you do something like $('.a').change(function { this.submit() }) it wont work. You must wrapp this in a jQuery object like $(this). Then you can call the sumbit on that.Locution
Warning : The form will NOT be submitted remotly (by ajax). Instead a full refresh will occurDamned
Can you please update or remove this misleading answer? Submitting a remote form in a non-remote way makes no sense. Gopal's answer is the correct.Rugen

© 2022 - 2024 — McMap. All rights reserved.