Home >Web Front-end >JS Tutorial >How to Submit Two HTML Forms Simultaneously with One Button?
In the HTML document, it is possible to have multiple forms with different actions. However, submitting them both individually can be inconvenient for the user. This article explores a solution to this dilemma by utilizing JavaScript to submit both forms simultaneously.
The first form, updateDB, is responsible for sending data to a database using PHP. Here's a sample HTML code:
<form>
The second form, payPal, directs the user to a payment page upon submission.
<form>
To submit both forms simultaneously, follow these steps:
function submitBothForms() { // Submit updateDB form asynchronously via XMLHttpRequest var xhr = new XMLHttpRequest(); xhr.open("POST", "mypage.php", true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(postData.join("&")); // Submit payPal form document.getElementById("payPal").submit(); }
async function submitBothForms() { // Submit updateDB form asynchronously via fetch() const res = await fetch("mypage.php", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new FormData(updateDB), }); if (!res.ok) throw new Error("DB Update Failed!"); // Submit payPal form payPal.submit(); }
By leveraging JavaScript, it is feasible to submit two forms with a single button. This approach provides a seamless experience for users, avoiding the need for multiple submissions. Remember to tailor the error handling and messaging based on your specific requirements.
The above is the detailed content of How to Submit Two HTML Forms Simultaneously with One Button?. For more information, please follow other related articles on the PHP Chinese website!