views:

144

answers:

3

How would I go about creating and posting a form POST request from inside some Rails code?
The use case I have is that I have received a form request, and I would like to forward this request on to a third party with my parameters intact.

I should add that I want to redirect the user out to the third party with the form too.

A: 

From ruby docs for Net::HTTP:

 res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
                              {'q'=>'ruby', 'max'=>'50'})

You could just pass params as the second arg, eg:

 Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'), params)
 redirect_to some_path

Also, don't forget to require the lib:

 require 'net/http'
 require 'uri'
Ben
This only appears to submit the form and return the response to my app. I want to send the user off with the form.
Neil Middleton
Then why not just have the form's action attr point to the url you'd like to POST them to?
Ben
Because I need to do some processing on the data before the third party
Neil Middleton
A: 

You might be able to do it this way:

  1. receive the post form the user
  2. change whatever data you mean to
  3. respond to the request with a form full of hidden fields
  4. automatically post that form to the third party via javascript on dom-loaded

Alternatively:

  1. set the form action to be the third party url
  2. intercept the onsubmit event with js
  3. change whatever data you need, either by simple client-side manipulation of the form
  4. or, post an ajax request to your app to treat the data, and replace the fields you need with from the ajax response
  5. with the data now massaged, let the form go through to the third party
kch
A: 

You're going to have to do this via Javascript, as there is no way of redirecting a POST request (as per the HTTP/1.1 protocol).

Mr. Matt