Submitting Multiple Forms with a Single Button
In web development, scenarios often arise where multiple forms need to be submitted simultaneously. However, traditional form submissions navigate the page away, hindering the submission of multiple forms. This raises the question: how can you submit two different forms using a single button?
Using JavaScript for Asynchronous Form Submission
To bypass the page navigation issue, we can utilize JavaScript for asynchronous form submission. This enables the submission of one form without affecting the other. The following JavaScript code can be used to submit two HTML forms, one after the other:
<script> // Get references to both forms var updateDBForm = document.getElementById("form1"); var payPalForm = document.getElementById("form2"); // Submit the first form asynchronously using fetch() fetch(updateDBForm.action, { method: updateDBForm.method, headers: { "Content-Type": updateDBForm.enctype }, body: new FormData(updateDBForm) }) .then(function(response) { // Submit the second form payPalForm.submit(); }) .catch(function(error) { // Handle any errors }); </script>
In this script:
This approach allows both forms to be submitted without interrupting the flow of the page.
The above is the detailed content of How Can I Submit Two Forms with One Button?. For more information, please follow other related articles on the PHP Chinese website!