i am trying to submit 2 forms at the same time
im trying to send 1 form to my DB and the other to a different site
my code is like :
function submitform(){
document.forms["form2"].submit();
document.forms["form1"].submit();
}
<form name="form1" action="1.php" method="post">
<!-- ... -->
</form>
<form name="form2" action="2.php" method="post" target="foo">
<!-- ... -->
</form>
<a onclick="submitform();">Go</a>
now if i submit only form2 it opens in a new tab and works but when i try to submit both of them it only submits form1
i have no idea why
any help would be appreciated
thank you
Only one form can be submitted at a time.
document.forms["form1"].submit();
document.forms["form2"].submit();
The first line is POST-ing an HTTP request to your server running PHP. The response will overwrite the current page, likely with a new HTML document. This means subsequent code is moot. Even if it begins to execute, any changes will not persist.
To get around this, combine the two forms into one, or use AJAX to get the information you need from the server "behind the scenes" (asynchronously) and update the page manually with JavaScript.
Marc B's comment
You can only submit a single format at a time. You'll have to combine the forms into a single one somehow prior to submission.
is the answer for me.
Using jquery you can call post your forms with ajax
function submit_forms() {
$.post('1.php', $('#form1').serialize(), function() {
// do stuff when finish
});
$.post('2.php', $('#form2').serialize(), function() {
// do stuff when finish
});
}
You will need to use an ajax request to submit at least one of the forms and some jasvcript to pause the form's submission while you send the ajax reques.
Using jQuery you'd use something like the following
<form id="theForm" method="post" action="your/formhandler/on/your/server">
<fieldset id="myInfo">
// form fields to post data to you in here
</fieldset>
<fieldset id="theirInfo">
// form fields to post data to the 3rd party in here
</fieldset>
<input type="submit" value="submit" />
</form>
It's more accessible to have everything ni one form with a proper submit button, but eth javascript technique (adjusted slightly) woudl also work with 2 separate forms and an <a>
tag.
$(function (){ // run this code once teh page has finished loading
$("#theForm").submit(function() {
$.ajax({
type: "post",
url: "http://their/form/handler",
data: $("#theirInfo").serialize() // off the top of my head I'm not 100% sure this will work, you may need to do $("#theirInfo").find("input,select,textarea").serialize()
})
});
})
Your form handler on your server will get sent all the data, but you can just ignore/discard the bits you don't need.