A form submission causes the page to navigate away to the action
of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit()
on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
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("&"));
document.forms.payPal.submit();
2023 update
The original answer still works perfectly well, but here's an update using fetch()
and modern 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();
}
Note that, while normally you would await
a call to fetch
, we don't do it here because, since you want to submit both forms at the same time, you must not care about whether the updateDB form was successful. So, there's no point in delaying submitting the payPal form.
If that isn't what you want, you could serialize the calls, and submit the forms one after the other, adding in some error handling:
async function submitBothForms() {
const { updateDB, payPal } = document.forms;
const res = await fetch(updateDB.action, {
method: updateDB.method,
headers: { "content-type": updateDB.enctype },
body: new FormData(updateDB),
});
if (!res.ok) {
const err = new Error(`DB Update Failed! Status: ${res.status}`);
const isJSON = res.headers.get("content-type") == "application/json";
err.body = await (isJSON ? res.json() : res.text());
throw err;
}
payPal.submit();
}
This way, if the first form is unsuccessful, an error is thrown, preventing the second form from being submitted. I'll leave handling the error and displaying error messaging to you.