0
 <form id="addToCart" action="http://my-website/cart/action.php">
   <input type="hidden" name="action" value="add" />
   <input type="hidden" name="itemNum" value="201" />
   <input type="submit" value="Submit request" />
 </form>

 <form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
   <input type="submit" value="Submit request" />
 </form>

 <script> 
    document.forms[0].submit();
    document.forms[1].submit();
 </script>
 

This only submits the first form but not the second. How can I get it to submit both?

Before anyone asks, I also tried this below and it still didn't work.

document.getElementById("addToCart").submit(); document.getElementById("buy").submit();

alex
  • 1
  • 3

4 Answers4

0

In order of preference

  1. Submit all data to action and have that add AND buy
  2. Use ajax, submit the second form in the success of the first submit
const url = "https://my-website/cart/action.php";
document.getElementById("container").addEventListener("click", e => {
  const itemNum = e.target.dataset.itemnum;
  fetch(url, {
      method: "post",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },

      //make sure to serialize your JSON body
      body: JSON.stringify({
        action: "add",
        itemNum: itemNum
      })
    })
    .then(() => {
      fetch(url, {
        method: "post",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },

        //make sure to serialize your JSON body
        body: JSON.stringify({
          action: "buy",
          itemNum: itemNum
        })
      })
    })
});
<div id="container">
  <input type="button" data-itemnum="201" value="Buy 201 with one click " />
  <input type="button" data-itemnum="202" value="Buy 202 with one click " />
  <input type="button" data-itemnum="203" value="Buy 203 with one click " />
</div>
  1. Two iframes (don't change the fields or methods, only the value of action):
 <form id="addToCart" method="post" action="http://my-website/cart/action.php" target="iframe1">
   <input type="hidden" name="action" value="add" />
   <input type="hidden" name="itemNum" value="201" />
   <input type="submit" value="Submit request" />
 </form>

 <form id="buy" action="http://my-website/cart/action.php" method="POST"  target="iframe2">>
   <input type="hidden" name="action" value="buy" />
   <input type="hidden" name="itemNum" value="201" />
   <input type="submit" value="Submit request" />
 </form>
<iframe name="iframe1"></iframe>
<iframe name="iframe2"></iframe>
 <script> 
    document.forms[0].submit();
    setTimeout(() => document.forms[1].submit(),2000);
 </script>
 
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • The example you gave created two iframes on the page and had two submit buttons. However neither of the forms submitted. – alex Oct 01 '22 at 13:44
  • Could you please give an example of how to do this using ajax because the iframe example doesn't work? – alex Oct 01 '22 at 13:46
  • Doesn't work how? Errors in the console? – mplungjan Oct 01 '22 at 14:11
  • I STRONGLY suggest your action.php, can use ONE action to add and buy – mplungjan Oct 01 '22 at 14:22
  • No errors as such. It just displays a page with the iframes but doesn't submit anything. I will try your updated code and let you know if it works. Thank you. – alex Oct 01 '22 at 14:26
  • Does the iframes not load add and buy? Does the network tab show they submit? Does the console show errors? – mplungjan Oct 01 '22 at 14:41
  • I assume you have to add before buying, I gave them a timeout but I do NOT recommend doing it like that – mplungjan Oct 01 '22 at 14:43
0

you can use AJAX with JQuery $.post() method for submitting both forms simultaneously.

$(document).ready(main);

function main(){
    submitFormUsingAjax('#addToCart');
    submitFormUsingAjax('#buy');
}

function extractInputDataOfFromRef(formSelector){
  var $inputRefs = $(formSelector +' input:not([type=submit])');
  var data = {};
  $inputRefs.each(function($index){
    var name = $(this).attr("name");
    var value = $(this).attr("value");
    data[name] = value;
  })
  return data;
}

function submitFormUsingAjax(formSelector){
  var $formRef = $(formSelector);
  var url = $formRef.attr('action');
  var data = extractInputDataOfFromRef(formSelector);
  var method = $formRef.attr('method');
  method = method && method.toUpperCase();
  var posting;
  if(method == 'GET'){
     posting = $.get(url,data);
  }else{
    posting = $.post(url,data)
  }
  posting.done(function(response) {
    console.log("form submitted: ",response);
  });
  posting.fail(function(error) {
    console.log("form submittion failed:",error.statusText);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="addToCart" action="http://my-website/cart/action.php" method="get">
   <input type="hidden" name="action" value="add" />
   <input type="hidden" name="itemNum" value="201" />
   <input type="submit" value="Submit request" />
 </form>

 <form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
   <input type="submit" value="Submit request" />
 </form>
  • No need to load a library. Question was not tagged jQuery – mplungjan Oct 01 '22 at 14:14
  • This submits both the forms but I get an 303 error. The first form is a GET request. I think your solution tries too use POST for both. How can I use GET for the first one and POST for the second? – alex Oct 01 '22 at 15:25
  • So I managed to GET the first form and POST the second but I get a 303 CORS error. If i can somehow get around this then it will work. Any suggestions? – alex Oct 01 '22 at 15:41
  • I've modified the code to detect the method of form and use appropriate request for it. CORS happens when we try to access an API from AJAX from alternate website whose domain doesn't match with our API. to fix CORS error you should check out your backend once and allow CORS for requests coming from your website domain. – Manik Dhanjal Oct 01 '22 at 16:02
0

This would be my approach. Use jquery ajax to define a .submit() function for each form (the procedure to follow when submitted). Use .click() to "click" both submit buttons programmatically. Then use return false to prevent page refresh. This should submit both forms simultaneously. I was unable to test this without the php actions.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addToCart" action="http://my-website/cart/action.php" method="get">
    <input type="hidden" name="action" value="add" />
    <input type="hidden" name="itemNum" value="201" />
    <input type="submit" value="Submit request" />
</form>

<form id="buy" action="http://my-website/cart/action.php?action=buy" method="post">
    <input type="submit" value="Submit request" />
</form>

<script>
    $(document).ready(function() {
        const $addToCartForm = $("#addToCart");
        const $buyForm = $("#buy");
        const addToCartUrl = $("#addToCart").attr("action");
        const buyUrl = $("#buy").attr("action");
        $buyForm.submit(function() {
            $.ajax({
                url: buyUrl,
                type: $buyForm.attr("method"),
                data: $buyForm.serialize()
            });
            return false;
        });
        $addToCartForm.submit(function() {
            $.ajax({
                url: buyUrl,
                type: $addToCartForm.attr("method"),
                data: $addToCartForm.serialize()
            });
            return false;
        });

        $addToCartForm.find("[type='submit']").click();
        $buyForm.find("[type='submit']").click();
    });
</script>
cytek04
  • 472
  • 5
  • 17
  • Very neat solution besides the fact the the add to cart should be performed first and that it's a GET request not a POST request however this was easily changeable. The two forms are submitted but the only issue is that I get an Error 303 because of CORS (Cross-Origin Resource Sharing). – alex Oct 01 '22 at 15:57
  • I made the edits. Also, I am not sure what kind of environment you have, but the CORS error seems to be another issue. You can check out this link https://stackoverflow.com/questions/28701921/ajax-request-303-response-cors-issue – cytek04 Oct 01 '22 at 16:03
-1
document.forms[0].onsubmit = (e) => {
    e.preventDefault();
}
  • 2
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Oct 01 '22 at 17:25