Submit two forms with one button - javascript

I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?
(Javascript is welcome)

You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}

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(f.elements[i].name + "=" + 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();

You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.

In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.

The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.

If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();

if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.

Related

Disable Button Call Server then Re-enable Button

I've seen many similar questions to mine, but have spent a few hours browsing and can't find the answer to my situation.
I have a Go based web-server. I have an HTML template page that lets me update the hardware clock and system clock on a 'nix system with the current browser time:
The update button is of type submit and calls the Go code which makes some system calls which take a few seconds, and I can't have this server code being called twice whilst it's still processing the first request.
So I want to disable the update button and then re-enable it once the server has responded.
I have jQuery, so I know I can have a function that is called via `onclick' and make these calls:
$("#updateButton").prop("disabled", true);
$("#updateButton").prop("disabled", false);
I have the form being submitted via the button (and not a jQuery call for instance - although I'm all ears) because I want the form to refresh when the server responds. So I have this:
<form action="/clock" method="POST">
...
</form>
This is so some values on the page get updated. Such as the status message at the top and the values in the various fields (updated to the values actually set).
The first problem I have is that if I call a JS function on the button click, and it disables the button as per above, then my server code doesn't get called! I have no idea why - could this be stopping the post request somehow?
<script>
function getTime() {
// Disable update button while waiting for response
$("#updateButton").prop("disabled", true); // Stops post request???
// How to re-enable update button?
}
</script>
And secondly, how do I re-enable the button? I don't know how to tell when the server has responded.
Since you're saying you want to disable the submit button once the button is clicked. And you're also saying you want the page to refresh while the form is being submitted.
<form action="" method="post" onsubmit="subBtn.disabled = true; return true;">
<input type="submit" name="subBtn" value="submit"/>
</form>
In the code above, when <form> is submitted, <input> field named subBtn is disabled and true is returned for <form> to continue the submission process. Once the page is reloaded, the button goes to its original state, which is enabled.
I am not sure whats going on the code down there or how/when is getTime() function executed, but return true; might just submit the form.
<script>
function getTime() {
$("#updateButton").prop("disabled", true);
return true; // this to continue with the original <form> process
}
</script>

JavaScript Text is not submitting form

I have a form called signup. I decided rather than having a button, I would have text with the use of JavaScript to submit, however the form is not submitting.
Finished
First, you should separate your Javascript from your HTML. Read More
You should post more code e.g. HTML.
Here's a working example to get a form to submit:
HTML:
<form id="signup">
</form>
<a class="submit" href="#">Submit</a>
Javascript
var form = document.querySelector('#signup');
var submitBtn = document.querySelector('a.submit');
submitBtn.addEventListener('click', function() {
form.submit();
})
https://jsfiddle.net/hpg6mnnr/
I think you can achieve what you are looking for with this
Finished
You could try achieving your objective using the javascript onclick event handler. Let me explain it to you with the help of an example, as below
<html>
<body>
Google
<script>
function f1() {
alert("f1 called");
//function f1()'s alert demonstrating additional functionality
}
window.onload = function() {
document.getElementById("link").onclick = function fun() {
alert("hello");
f1();
//executing an initial "hello" alert
}
}
</script>
</body>
</html>
Here we create a link and give it an ID of link. Suppose we need it to execute some functionality when it's clicked. All fine for now.
Now after the document is loaded (as demonstrated by window.onload) we wait for the link to be clicked. If it's clicked, we execute the onclick event which gives an alert "Hello". Further suppose you wanted to execute some extra functionality with the click of your link (like submission of a form, as in your case), so we demonstrate it here using the f1() method. As you might see we execute all of these simultaneously simply by using the onclick event handler.
Well, you have several ways to do it!
Firstly verify if there is not another HTML element with the same id as you form, because if it has, you have two problems, one your HTML is not well formatted, second it may be defined first than the tag and of course, the document.getElementById('signup') will catch it firstly. Also if the page hasn't been loaded by complete, it won't find the element, try (see form down below):
window.onload = function () {
var aBtn = document.getElementById('myA');
aBtn.onclick = function () {
document.getElementById('submit').submit();
}
}
Another reason but less probable is, your active scripting (javascript for example) may be disable.
Verify it just in case:
Internet Options -> Security Tab -> Custom Level -> Scripting -> Active Scripting -> [Enable]
I've just copied your code and it worked for me.
E.g.:
<form id="signup" action="http://google.com">
go
</form>
You also can use onclick="document.getElementById('signup').submit();" or go with a button or input type="submit"
E.g.:
<form id="signup" action="http://google.com">
go
<input type="submit" value="go2">
<button>go3</button>
</form>
Well, there is other ways to do it but I think those are enough!

Use javascript AND PHP in one <input> tag?

I feel like I've looked around for the answer for this question, but most of the responses are very hacky: involving javascript that pops in via AJAX, redirects and other ways of modifying the DOM on the fly.
What I want to do is make the submit button disappear when a user submits a document (javascript) and submit the message via mail (php). The code I have is the following:
<form action="" method="post">
...
<input onclick="removeElements()" id="subButton" class="submit" name="submit" type="submit" value="submit">
The php mail function is in the same document.
Here is the removeElements() function:
var el = document.getElementById("subButton");
el.remove();
document.getElementById("thankYouMessage").setAttribute("style", "display:block");
The submit function works without the javascript call, but when I add the onclick="removeElements()" part, then the javascript part starts working, but the php is no longer executed.
I know that there are other methods for doing this, but in this case, I'm actually curious about why this doesn't function as I had planned. By removing the submit button, am I in effect killing the child PHP process mid(or pre)-execution?
Thanks!
If you add onclick you will have to fire the submit manually.
The other option is add your javascript call code in onsubmit="removeElements()" on the form tag. This way, it will execute your code after executing submit
Related question here
Don't remove the button, rather set visible: hidden or display: none for its style. This way it will still be in the document and will work, it just won't be shown.
When you send the form reloads your page so I suggest:
Using Ajax and only delete button on the response, or
Not generate the button when reloads your page.
Jquery Ajax examples: You can see them here api.jquery.com/jquery.ajax/
Regards.
You could simple use the .hide functionality which JQuery gives you. It's very simple to use and very clean.
Example1 using JQuery:
$("#FormID").submit(function(e)
{
e.preventDefault();
// Hide button
$("#subButton").hide();
// Display thank-you message
$("#thankYouMessage").css("display", "block");
});
Example2 using JQuery:
$(document).ready(function() {
$(".submit").click(function() {
$("#subButton").hide();
$("#thankYouMessage").css("display", "block");
return false;
});
});

Javascript submit function working and not working

I hesitate to ask this as it is a bit complex, but I will try to make it simple.
I have a page with several form fields.
I submit the page via a submit script (note more is done in this submit script, but I am leaving it out for simplicity
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;
alert(gonext);
f.submit();
}
Please note that there are other variables included in this function. gonext is not the only one, but I am leaving the others out in this case to keep it simple.
My HTML for simplicity sake looks like this:
<form name="file_form" id=file_form action="<?= $this->URL('#', 'UpdateUploadUser', array('mode'=>'upload', 'ID'=>$_GET['ID']));?>" method="post" enctype="multipart/form-data">
<input type="text" name="oneitem">
<button name="submit1" id="submit1" onclick="do_file_form_submit(2);"><img src="<?=$theme;?>/images/12addphoto32px.png">Save Settings Then Upload/Register Another</button>
On the backend side within the "UpdateUploadUser" function we have a checker which checks each submitted field to see if it is empty or not. If it is empty, it returns:
$this->chk = new mVal($event);
if(!$this->chk->Validate()) {
$this->mode = 'error_redisplay';
//$this->mode='Error';
return;
}
If all info is there, then the script continues and runs as expected. So, here is the issue.
If all information is there, and I click the button, then all works fine. The file_form submit JS ALERTS the gonext value and the script runs and updates as it should.
HOWEVER, if an item is missing, then the validation script runs and "RETURNS".
Once the page has been returned, if you THEN attempt to click the submit button, the page STILL submits as it should, but the file_form submit script seems as if it doesn't even run, so that the gonext value is not passed at all.
So, I am trying to figure out how the submission of the form is still happening apart from this do_file_form_submit script. Is there something having to do with "return" that I don't know about?
Hope that makes sense and thanks for any help!
Craig
Review your code
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;//f.gonext. i can not find gonext in ur form. just oneitem try something like f.oneitem.value = gonext; i believe that is where the //problem occurs
alert(gonext);
f.submit();
}
in nutshell, replace the line:
f.gonext.value = gonext;
with
document.file_form.value = gonext;
and then submit like
document.file_form.submit();

onBeforeUnload and multiple forms

I want to have a feature to submit several forms on a page when the user leaves the page. There is this "do you wanna save?" question and my code so far is like this:
function checkForChanges( ) {
if (window.formform1Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form1.submit();
}
}
if (window.formform2Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK.")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form2.submit();
}
}
}
It may seem a little bit of overkill but it is generated automatically by our template engine and may be extended to more forms.
The body tag:
<body
onLoad="init();
window.formform1Changed=false;
window.asked=false;
window.doSaveForms=false;
window.formform2Changed=false;"
onbeforeunload="checkForChanges();">
And interesting part of one of the forms (the other one looks identically:
<input value="xyz" id="la" onchange="window.formform1Changed=true;" />
<input name="save" onclick="window.formform2Changed=false; window.formform1Changed=false;" type="submit" value="save" />
Now to the problem:
If I change values in both forms and navigate away from the page, the question from the first form pops up. I click OK, the form is saved but the form1.submit() triggers a new onBeforeUnload event which breaks the whole logic of my idea.
The question now would be if there is a way to submit all forms on a page when only asking one time when the user navigates away?
Any help is highly appreciated!
Thanks.
Form submissions requires post-back, once you submit the first form, your page is redirected to the "action" of that form and you will lose the information in the rest of the forms you have.
Having multiple forms on the page is not the best idea, however, if you absolutely have to have them, the way to save all of them would be to replace full post-back with an AJAX call to a web-service (or a stand-alone page, that accepts query string parameters, though it's not as secure or flexible way). That way you can submit each form over the AJAX call without page redirecting.
As SLaks said, you will not be able to submit multiple forms in the way you are trying. You do have some other options though. Instead of traditional form submits you could make some kind of ajax calls to save the form data you care about. Here is an example using jquery and php (link)

Categories

Resources