Reputation: 31064
I'm porting an existing app to rails that makes extensive use of stylized anchors for form submission:
<a class="lozenge-button h25 blue" href="#">
<span class="left"></span>
<span class="center">Send</span>
<span class="right"></span>
</a>
However in Rails these anchors won't work for Ajax form submission, since Rails' UJS seems to require an input tag rather than an anchor (i.e. submit_tag("Submit", remote: true)
).
Is there a way to make my anchors fire the Ajax form submission? I managed to get the anchor to submit the form with the following:
$('#my_anchor').click(function() { $(this).closest('form').submit();});
... but it bypasses Ajax and does a normal form submit that reloads the page.
Upvotes: 2
Views: 1126
Reputation: 973
In Rails, you add remote:true to your link helper method. Then rails_ujs, (Rails unobtrusive javascript) takes care of sending it via ajax. See The Rails Ajax Guide so your code would become (in ERB)
<%= link_to the_rails_path,remote:true,class:"lozenge-button h25 blue" do %>
<span>etc</span>
<span>etc</span>
<%end%>
Upvotes: 0
Reputation: 31064
I ended up solving it in a way very similar to this question:
<%= f.submit id: 'hidden_submit_button', style: 'display: none;' %>
<a class="lozenge-button h25 blue" href="#" onclick="$('#hidden_submit_button').click(); return false;">
<span class="left"></span>
<span class="center">Send</span>
<span class="right"></span>
</a>
Upvotes: 1
Reputation: 5437
You can try this
var form = $(this).closest('form');
$.post(form.attr('action'), form.serialize());
Upvotes: 0