简体   繁体   中英

Submit button for second form submits first form on page

I'm trying to include two forms on the same page. Below is much simpler than what I want to do, but it has the same error.

 <div class="content-form"> <form id="b_form" name="form_b" class="form" method="post"> </form> <form id="a_form" name="form_a" class="form" method="post"> <input type="number" id="field_quantity" name="quantity" class="form-control" /> <button type="submit" form="a_form" name="__action" value="new_shipment" class="btn btn-submit btn-success">Submit</button> </form> </div> 

The code snippet is actually a smarty template that gets included in a larger page. I think the issue is contained within this code though because the rest of the page has div tags, so it's not like I have a nested form.

The issue: When I click the submit button, I echo the $_POST object on the php page that handles the request. Even when the quantity field is filled in, I still get {"__action":"new_shipment"} as the contents of the $_POST.

If I swap the order of the two forms, then the $_POST does indeed contain the quantity field. Why does the submit button in the second form not submit the fields in the second? How do I fix it?

So, there are different ways to handle this. I went here http://phpfiddle.org , clicked on the Window tab, choose HTML Form and pasted your html and added some input on the first form:

<form id="b_form" name="form_b" class="form" method="post"> 
    <input type="number" id="field_quantity_b" name="quantity" class="form-control" />
    <button type="submit" form="b_form" name="form_b_btn" value="new_shipment" class="btn btn-submit btn-success">Submit</button>
</form>

<form id="a_form" name="form_a" class="form" method="post"> 
    <input type="number" id="field_quantity_a" name="quantity" class="form-control" />
    <button type="submit" form="a_form" name="form_a_btn" value="new_shipment" class="btn btn-submit btn-success">Submit</button>
</form>

Then I added this

<?php

    if($_POST && isset($_POST['form_b_btn'])) {
        echo "FORM B ";
        print_r($_POST);
    }

    if($_POST && isset($_POST['form_a_btn'])) {
        echo "FORM A ";
        print_r($_POST);
    }
?>

You need different values for the name of your submit buttons. Then when you check the $_POST, you verify which form was submit. There are other methods, like specifying different actions and then having different files to handle them. This may help you: How to place two forms on the same page?

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