Posted by Vince Wadhwani on Jun 21, 2007

I recently started playing around with Paypal for one of my sites. The snag is I’m using paypal’s standard html to submit the form but I also need to use a little ruby to save some items to my database. Well, how does one submit two forms with just one button? Read on and I’ll tell you.

The answer turns out to be with javascript. So if you’ve got a requirement that this has got to work without javascript.. you’d better hit The Google again and look for another solution because we need javascript to pull this off.

At the stop of your Rails view file, but this little snippet of javascript:

<script language="javascript" type="text/javascript">
function submitForms(){
document.form1.submit();
document.form2.submit();
}
</script>

You can then start your paypal form (which starts like this:

<form name = form1 target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" >
--paypal code here --
</form>

Your second form is your rails form. You need to also start it in HTML but after that you can mix in some ruby. Here’s what I did:

<form name=form2 target="_self" method="post">
<% if request.post? %>
-- insert your ruby code here --
<%end %>
</form>

Now, when you click submit, both the forms will be executed. Some action will be taken on your local app and you’ll also open a new window over to paypal.

As it turns out it’s not a perfect solution for my paypal woes, but it’s still a nifty trick which you can apply to a lot of different situations where you’ve got multiple forms and a single submit button!