Thursday, November 19, 2009

Rails redirect_to with POST?

During the development of a small application we needed to redirect to an other website and POST some values to that specific url. That was harder than expected.

The first idea in my way to solve this was to use redirect_to. But the requirement is to use the http POST method. Redirect_to can't POST! It also seems that the http specification doesn't support POST redirects, so that's a good reason.

But how to get it done then? After some googling I found a way to "redirect" via a post. The browser has to do it! Put a form on a page, the fields/parameters to be posted in it and let it submit on load. To hide the visibility of fields I made them hidden (that's common, I'd say).

The simplified code of the page:


<h2>Back to the shop....</h2>

<script type="text/javascript">
Event.observe(window, 'load', function() {
document.forms[0].submit();
});
</script>


<% form_tag @merchant.redirect_url, :method => :post do %>

<%= hidden_field_tag :paid, @paid %>
<%= hidden_field_tag :order_id, @payment.merchant_order_id %>

<% end %>


I'm not a Javascript developer yet, but I think this code is neat and straightforward. When the window/body is loaded it fires a submit on the first form. Normally the one and only one available.

Unfortunately I wasn't able to find this solution easily. So I hope it helps you!

<

No comments:

Post a Comment