简体   繁体   中英

How do I automatically submit two forms without the page refreshing?

 <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();

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>
 

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>

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>
document.forms[0].onsubmit = (e) => {
    e.preventDefault();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM