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

How Can I Submit Two Forms Simultaneously with a Single Button?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 01:07:11317browse

How Can I Submit Two Forms Simultaneously with a Single Button?

Submit Two Forms with a Single Button

Submitting two forms with one button may seem like a straightforward task, but it's not possible using traditional form submission methods. This is because submitting a form navigates away from the current page to the action specified in the form.

The Solution: Asynchronous Form Submission

To submit both forms simultaneously, we need to bypass the traditional form submission process. We can achieve this by submitting the first form asynchronously via JavaScript, allowing us to submit the second form without interfering with the first.

JavaScript Async Form Submission:

The following JavaScript code demonstrates how to submit the first form asynchronously:

var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
    postData.push(encodeURIComponent(f.elements[i].name) + "=" +
        encodeURIComponent(f.elements[i].value));
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));

Once the first form is submitted asynchronously, we can immediately submit the second form using the standard form submit() method:

document.forms.payPal.submit();

Updated Solution (2023):

The updated solution utilizes fetch() and modern JavaScript syntax:

function submitBothForms() {
    const { updateDB, payPal } = document.forms;
    fetch(updateDB.action, {
        method: updateDB.method,
        headers: { "content-type": updateDB.enctype },
        body: new FormData(updateDB),
    });

    payPal.submit();
}

This updated solution provides a more concise and performant implementation compared to the original answer.

The above is the detailed content of How Can I Submit Two Forms Simultaneously with a Single Button?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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