I'm trying to submit 2 forms at the same time, using javascript. However, it seems like only the 2nd submit is opened, and not the first.
The code is fairly simple:
<html>
<body>
<form id="report_0" method="POST" target="_blank" action="https://www.google.com">
<input type="hidden" name="test1" value="1">
<input type="submit" value="report_0">
</form>
<form id="report_1" method="POST" target="_blank" action="https://www.google.com">
<input type="hidden" name="test2" value="2">
<input type="submit" value="report_1">
</form>
<script>
document.getElementById("report_0").submit();
document.getElementById("report_1").submit();
</script>
</body>
</html>
I cannot use ajax or equivalent as it has to be the 'native' POST (due to CORS issues)
I've read somewhere that you can't submit 2 forms at once, this doesn't make sense to me. I've tried changing the target from "_blank" to "form1" & "form2" but still nothing.
Your assistance will be highly appreciated :)
EDIT
Here is what I actually use:
for (....) {
var form = document.createElement("form");
form.setAttribute("name", "report_"+i);
form.setAttribute("method", "POST");
form.setAttribute("target", "_blank");
form.setAttribute("action", action);
for (var key in parms) {
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", key);
field.setAttribute("value", parms[key]);
form.appendChild(field);
}
console.log(form);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
Not the prettiest way of doing it, but I thought it would be nice to share it anyways. I ended up solving it by using setTimeout
:
var requestDelay = 2000;
document.getElementById("form-a").submit();
setTimeout(function() {
document.getElementById("form-b").submit();
}, requestDelay);
This way, it waits until form A
(probably, with an estimation of 2 seconds) has been submitted, and then submits form B
. You might need to play around with the requestDelay
to fit your needs.
You can't do it this way. When a form is submitted, the whole page is "destroyed" and the form's response loaded as a new page.
JavaScript code runs single-threaded so basically you're triggering the submit event on two forms at once and only when your JS is done, the browser takes over again and tries to perform the task queue you gave to it.
So if you would like to submit both forms "normally" in a non-AJAX way, you'd have to:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With