Reputation: 1
I try to submit 2 forms with a one submit button, but it doesn't work I get only the second form, please help me this is the code jQuery:
$('#BTN1').click(function() {
$('#form1').submit();
$('#form2').submit();
});
Upvotes: 0
Views: 98
Reputation: 103
why not ajax submit the form...
$('#BTN1').click(function(e) {
$.ajax({
type: "POST",
url: UrlToPost,
data: $('#form1').serialize(),
success: function(msg) {
}
})
$.ajax({
type: "POST",
url: UrlToPost,
data: $('#form2').serialize(),
success: function(msg) {
}
})
});
// Please note your BTN1 shouldn't be a type submit or it will refresh the page.. or you can put
e.preventDefault()
as the first line inside your click function.. to avoid referesh
Upvotes: 0
Reputation: 4412
As is said in other answers, once the browser successfully submits a form, anything else happening on the page is lost when the new page loads. So once form1 submits, everything that happens after that in your script is lost.
There are a few different ways you can handle this. Since your tags say you're using jQuery, I you can easily use ajax to post the forms, wait until they're both done, and then switch to whatever new url you want.
$('#BTN1').click(function() {
var form1done = false;
var form2done = false;
$.post( $('#form1').attr('action'), $('#form1').serialize())
.done(function(r) {
form1done = true;
if(form2done)
location.assign('/target/location');
}).fail(function() {
// handle error
});
$.post( $('#form2').attr('action'), $('#form2').serialize())
.done(function(r) {
form2done = true;
if(form1done)
location.assign('/target/location');
}).fail(function() {
// handle error
});
});
Look at the documentation for $.post and .serialize for more information.
That said, this is still going to be a clunky way to run a page. You're probably better off either refactoring into a single form, or else going full ajax and just handling the results of the form submission in the same page.
A final option would be to change the target
attribute of your forms so that they open in new windows. That will allow both of them to complete submission.
Upvotes: 1
Reputation: 802
This is happening because only one request will make it to the server. When your first form is being submitted, the second form interrupts it and starts.
You need to handle it in a different way. Do something with the first form first (send an AJAX request yourself instead of relying in the browser), wait till it's finished and then start with the second one.
Since AJAX requests are asynchronous you can even do them in parallel.
Upvotes: 0