Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form using link_to in rails

I'm trying to submit a form using link_to as follows:

 <%= form_for(@post,  :url=> '/post/action', :method=> 'post', :html => {:id=>'form_id'} ) do |f| %>
  ....

 <%= link_to 'submit', "/post/action", :onclick=>"document.getElementById('form_id').submit()" %>

  ....

but it is not posting the form, it is simply redirecting my form to the specified url. Does anyone know how to do this?

like image 348
random Avatar asked Jul 25 '12 07:07

random


2 Answers

You can use:

<%= link_to 'submit', "#", :onclick => "$('#form_id').submit()" %>

if you are using JQuery and a later version of rails.

Above will work but if you have a really long page it will navigate to top of the page because of "#" so if you want to avoid that you can do:

<%= link_to 'submit', "", :onclick => "$('#form_id').submit()" %>
like image 153
Paulo Fidalgo Avatar answered Oct 17 '22 22:10

Paulo Fidalgo


I think both things happen. The browser starts to submit the form, but it also follows the link's href. You can fix it by linking to # instead of /post/action...

...however, I don't recommend doing it. There are a few better approaches:

First, you can use a button instead of a link. You'll have to style it to make it look like a link, but that should not be a problem. It will be better, because it won't break the Principle of Least Surprise (people who read the code expect forms to be submitted with buttons) and you won't need the JavaScript.

If you insist on using a link, you should at least move the JavaScript code from the view to a JavaScript file. Then have this behavior added unobtrusively (although, you won't have a good fallback with the link). Assuming you're using jQuery, it should be as simple as:

$(document).on('click', '[data-submit-form]', function(e) {
  e.preventDefault();
  $(this).closest('form').submit()
}
like image 8
Stefan Kanev Avatar answered Oct 17 '22 23:10

Stefan Kanev