mridula
mridula

Reputation: 3281

Rails: Changing form method to PATCH in javascript sends a GET request on form submit

I have a form which by default is a POST. On change of a drop down, I want to change the form method to PATCH and its action to something else and submit the form.

erb:

<%= form_for @booking, :url => admin_events_bookings_path, :html => { :class => 'smart-form', :id => 'mainForm', :data => { :change_event_path => change_event_admin_events_bookings_path } } do |f| %>
...
<% end %>

HTML (rendered):

<form class="smart-form" id="mainForm" data-change-event-path="/admin/events/bookings/change_event" action="/admin/events/bookings" accept-charset="UTF-8" method="post" novalidate="novalidate"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="oC9bO0GVnMuc4UFnJLKDbTvaWEPLCKycmrsTJGWcHyYZ2QrYsVzbvP1pmMmqF/LIT3BepGCTWhZ0YZyPGsJUPg==">
...
</form>

JS:

$('#booking_event_id').on('change', function(ev) {
    $('#mainForm').attr('action', $('#mainForm').data().changeEventPath) //this works, verified in browser
    $('#mainForm').attr('method', 'patch') //this works, verified in browser
    $('#mainForm')[0].submit()
})

However the request that reaches the server is a GET request. From the log:

Started GET "/admin/events/bookings/change_event?utf8=%E2%9C%93&authenticity_token=oizowirdfSiR%2BiUGIsZWe8PHSypUAItFK8Y39gwNtK4b2rkh2hQ6X%2FBy%2FKisYyfet21Nzf%2Bbfc%2FFHLhdc1P%2Ftg%3D%3D&ticket_type=priced&booking%5Bevent_id%5D=2"

Why does the form submit as a GET request? How can I make this work?

Upvotes: 2

Views: 1724

Answers (1)

R. Sierra
R. Sierra

Reputation: 1205

According to Rails docs:

If the verb is not GET or POST, which are natively supported by HTML forms, the form will be set to POST and a hidden input called _method will carry the intended verb for the server to interpret.

So to change the verb, you only need to add a hidden field to the form named _method with the value patch or put:

<input type="hidden" name="_method" value="patch">

Upvotes: 4

Related Questions