使用JS提交表单并仍然成功发布所有表单数据的正确方法是什么?

问题描述:

I'm working with an embedded app on our dev site and when I click the submit button inside the iframe, I am triggering a manual submission event on another form (not in an iframe) on that page. If I manually click the submit button for the form, my data posts and everything works correctly. However, I want to eliminate an extra user click and submit the external form automatically when a user submits the other form inside the iframe.

I've got everything working correctly on a base level. When a user clicks the submit button in the iframe, I am using JQuery to grab values from inside the iframe and set values in this external form. Using the jquery 'submit()' event, I am then able to submit that external form. The problem is, the page refreshes and the data doesn't go anywhere. If I remove the 'submit()' event and manually click the submit button, the form posts and in this case, adds a product with custom data to the product cart.

As a proof of concept, this is my 'iframed' HTML.

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <h1>Proof of Concept</h1>
        <p>Total cost: $<span id="cust_price">222.22</span> plus shipping.</p>
        <p>Quote number: <span id="quot_num">1546751962211</p>

        <form method="POST" enctype="multipart/form-data" id="newQuoteForm">
            <button type="submit" class="btn btn-primary" name="new-app-btn">Add to Cart</button>
        </form>
    </body>
    <footer>
    </footer>
</html>

Here is my on-page form that is OUTSIDE the iFrame.

<form method="POST" enctype="multipart/form-data" id="outer-quote-form" action="/checkout/">
    <label class="quote_number">Quote Number: 
        <input type="text" id="quote_number" name="quote_number" value="">
    </label>
    <label class="custom_price">price:
        <input type="text" id="custom_price" name="custom_price" value="">
    </label>
    <button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>

Then, I have JQuery working to grab the iframed values and puts them in the exterior form. Afterwards, it fires a 'submit()' event on that form.

<script>    
    jQuery('#newQuoteApp').load(function() {
        var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
        jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() { 
            jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
            jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());

            jQuery("#outer-quote-form").submit();
            return true; //return false prevents submit
        });
    }); 
</script>

Except when the jquery submit() event fires, the form appears to submit and the page refreshes but no data is posting as it does when I manually submit the form. Is there an extra step here or a better way to fire the form submit with post data?

Edit: Adding the PHP function that isn't firing on jquery submit() for context.

if (isset($_POST['ws-add-to-cart'])) {
    add_action( 'init', 'add_product_to_cart' );
    function add_product_to_cart() {
        global $woocommerce;
        global $product;
        $product_id = 138;
        $woocommerce->cart->add_to_cart($product_id);
    }
    header("Location:https://www.devsite.com/checkout/");
}

The reason for the form not submitting because you are submitting the whole form without the submit button which is
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
which you have declared in php to get a post request like this

if (isset($_POST['ws-add-to-cart'])) {...

When you call submit(); on the form via the get method, you see
'/new-quote/?quote_number=1546751962211&custom_price=222.22'
but where's ws-add-to-cart, it's not submitting and that's the reason why php isn't getting your request

The fix will be to add .click() on the submit button instead of submitting the form

<script>
  function enterVals($val){
    var price = $val.price;
    document.getElementById("quote_number").value = $val.num
    document.getElementById("custom_price").value = $val.price
    document.getElementsByName("ws-add-to-cart").click();
  }
</script>

Or in your script in case you want to use jquery, this is the fix

<script>    
    jQuery('#newQuoteApp').load(function() {
        var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
        jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() { 
            jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
            jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());

            jQuery("button[name=ws-add-to-cart]").click();
            return true; //return false prevents submit
        });
    }); 
</script>

This is definitely the answer and sorry for my stupidity, i didn't pay required attention before

try removing return true from your js code
if that doesn't work, try changing the <form method="POST" to <form method="GET" to debug the values in the url just for checking that the form actually fires up with values

Alternative method: Old school method

code for page OUTSIDE the Iframe

<script>
  function enterVals($val){
    var price = $val.price;
    document.getElementById("quote_number").value = $val.num
    document.getElementById("custom_price").value = $val.price
    document.getElementById("outer-quote-form").submit();
  }
</script>

code for the Iframe file

<script type="text/javascript">
    $('#newQuoteForm').on('submit', function(event) {
        var Page = window.parent;
        var allVals = {
            price:$('#cust_price').text(),
            num:$('#quot_num').text()
        }
        Page.enterVals(allVals);
        event.preventDefault();
    });
</script>

Explanation

window.parent refers to the parent window where the iframe is loaded on, with reference to this we can trigger functions that are in the parent window so by this, we created a variable and added the information which is sent by the function enterVals() to the window
The enterVals() function just puts the values and submits the form without any jQuery.

What is the proper way to submit a form with JS?

This might not be the 'best' way to submit a form with js but is cross-browser which is good