How to submit 2 forms in one page with a single submit button

You have SEVERAL issues

  1. input type=image IS a submit button so you are trying to submit something from a non-existing form, likely the same page you are on

  2. when you submit form1, it replaces the current page, if you manage to submit form2 as well, it is VERY likely to interfere with the submission of form1

Here is what you can TRY (plain javascript):

<script language="javascript">
function submitForms() {
  document.getElementById("firstform").submit();
  document.getElementById("secondform").submit();
 }
</script>

<form id="firstform" target="iframe1">
</form><iframe name="iframe1" style="display:none"></iframe>
<form id="secondform" target="iframe2">
</form><iframe name="iframe1" style="display:none"></iframe>
<button typ"button" onclick="submitForms()"><img src="https://stackoverflow.com/questions/9096515/images/order-button.png" "/></button>

Alternatively AJAX the forms one at a time (assumes jQuery loaded)

DEMO HERE

$(document).ready(function() {
  $("#subbut").click(function(e) {
    e.preventDefault(); // or make the button type=button
    $.post($("#firstform").attr("action"), $("#firstform").serialize(), function() {
      $.post($("#secondform").attr("action"), $("#secondform").serialize(),
        function() {
          alert('Both forms submitted');
        });
    });
  });
});

UPDATE: If you want two form’s content to be submitted to one action, just add the serialises:

$(document).ready(function() {
  $("#subbut").click(function(e) {
    e.preventDefault(); // or make the button type=button
    $.post($("#firstform").attr("action"), $("#firstform").serialize() + $("#secondform").serialize(), function() {
      alert('Both forms submitted');
    });
  });
});

PS: The PHP in the demo is just echoing back what you post. There is no special action needed on the server.

Leave a Comment