Quick tip: Submit Two Forms w/ One button
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!
This is risky business, I wouldn’t try to submit two forms at once. Not safe.
Eugenia
This is risky business, I wouldn’t try to submit two forms at once. Not safe.
Eugenia
Heh, did you leave the comment twice to reinforce that? ;)
I agree it’s not the best thing and I’d never recommend that you do it if there’s another way. But I tested it quite thoroughly over and over to make sure it worked each and every time.
Anyone employing this method should also do the same, though as you say, the best thing would be to avoid it if possible.
vince
No, but your form wouldn’t respond.
Also, originally I could not post without javascript being active. I have my JS OFF on my G4 powerbook because the web is too slow these days because of too much JS used. A good code would use Ajax when JS is available, and it would take the traditional route when it’s not.
Eugenia
I’ve disabled non-javascript commenting… It’s an anti-spam measure built into Typo 4.1.1.
vince