Home > Web Front-end > JS Tutorial > How Can I Submit Two Forms with One Button?

How Can I Submit Two Forms with One Button?

Mary-Kate Olsen
Release: 2024-11-30 22:24:13
Original
994 people have browsed it

How Can I Submit Two Forms with One Button?

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>
Copy after login

In this script:

  1. We retrieve references to both forms using the getElementById method.
  2. The fetch() function is used to submit the first form asynchronously.
  3. Once the first form is submitted successfully, we trigger the submission of the second form.
  4. We handle potential errors in the catch block.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template