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
This is legacy code.
I'm working on a project where we're using iframes to simulate AJAX.
Basically, we're using the target attribute to submit the <form> in an iframe, resulting in the request not opening a new tab. Also, we echo a <script></script> in the response from the PHP, and the result is executed since it populates the iframe.
Here's an example of such <form> :
<form id="form_to_submit" method="POST" action="ajax/createUser" target="iframe_name">
<input type="text" name="input_to_send">
<button type="button" onclick="$('#form_to_submit').submit()">Submit With Onclick!</button>
</form>
Nowadays, not only this looks evil, but it has one (perhaps others) huge pitfall. If one request is made through this process, and the client goes somewhere, and then goes back in his browser history, it'll send the request again.
To fix this last problem, there are many solutions. I think the one I prefer the most is to use real AJAX instead of iframes. Now, in theory, I could change every single form in the source code to make it use AJAX, but I know I won't have 1 straight week of work just for this purpose.
I'm looking for a "quick" way to intercept these requests before they're sent to the iframe, and send them with AJAX instead.
So far, I tried to target <form> tags which have a target="iframe_name" and listen to the submit event to then send the request again with a same method/URL/data.
$('form[target=iframe_name]').on('submit', function (event) {
event.preventDefault(event);
var url = $(this).attr('action'),
datas = $(this).serialize();
$.post(url, datas).done(function (response) {
eval($(response).text());
});
});
But that only works if they're submitted through a real click on a submit button. I'd say 95% of these cases are submitted through onclick tags which will .submit() the forms, and in these cases, the submit event won't trigger it appears.
I'm stuck, any idea ?
Note : I'm tagging jquery only to let you know it's available to be used, even though the question is still relevant with any lib/framework of JS.
You can actually remove the onclick attributes just by doing a general jQuery action on document ready:
<script>
$(document).ready(function() {
var getButton = $('form').find('button');
getButton.prop('onclick',null);
// put listener script here for new form submit (using ajax)...
});
</script>
This piece of code just does a general lookup on the page for all forms, finds the buttons, then removes the onclick attribute. Once you do this the form should not submit anymore with that inline javascript.
I would suggest this be temporary as you incrementally change the forms over time to natively work using the jQuery listener (like the other 5% of forms you have created with no onclick).
Im trying to track when a user hits the submit button on a contact form.
The page's URL doesn't change, its static.
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
Do I need to edit my analytics account?
Where do I add the additional javascript?
UA is installed correctly (analytics.js)
I'm new to GA and javascript so please break it down for me.
Thanks
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
That is a bit of a non sequitur. Even when the Url does not change there is probably some stuff happening - before you send it there is probably some form validation, and there is some action behind the scene to send there form, like e.g an ajax call.
You could attach event tracking to a submit handler:
<form onSubmit="ga('send','event','category','action','label')">
<input type="text" id="text" name="text">
<input type="submit">
</form>
However this would just tell you that somebody hit the submit button, not if they filled in the form correctly or if the form actually has been sent.
Now I enter speculation land, because I do not know how your form actually works - maybe you can show us an url or give more information.
But maybe you have a validation function that is called on the submit action of the form to see if the form is filled in correctly. In that case it would be advisable to do the tracking in the validation function (horribly simplified example, not production code):
<form onSubmit="validate()"><input type="text" id="text" name="text"><input type="submit"></form>
<script>
function validate() {
var test = document.querySelector('#text').value
if(test = "") {
ga('send','event','Form','Submit','Submitted, but not filled in');
return false;
}
ga('send','event','Form','Submit','Submitted with correct values');
return true;
}
</script>
That's a tad better, at least it tracks the difference between correct submissions and invalid submissions.
Even more speculation: If your form is sent without page reloads it uses probably an ajax call, and there is a huge probability that is uses jQuery (I say that because a) it really is probable and b) it's easier to construct an example in jQuery. The same can be achivied with other libraries or in native JS, but the example will produce an error if you do not use jQuery).
jQuery has a thing called "global ajax handlers". "Global" means they are not callbacks for a specific action, they hook into jQuerys ajax "mechanism" whenever a call to an ajax function is made. The following might work if you have only one aja event per page (else you need logic to distinguish the different ajax event e.g, by checking the url they are being send to), and allows you to track if the ajax call has returned successfully, like when your form data has been send to the server and the request return a 2xx status code:
$(document).ajaxSuccess(function() {
ga('send','event','Form','Submit','Yeah, form data sent to the server');
});
However this does not tell you if the data has been processed correctly. For that you need to make the server emit a success message and check the response:
$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "formprocessor.php" ) {
if(xhr.responseText.indexOf("success") > -1) {
ga('send','event','Form','Response Received','Form data processed ');
} else {
ga('send','event','Form','Response Received','Form data NOT processed ');
}
}
});
The global ajax event handler is attached to the document - you can put that anywhere on your page, it will do nothing unless an ajax event was called.
Again, this is not production code. Do not try to copy and paste.
This was certainly a bit much if you are new to this, but it should at least help you to improve the question and to see what kind of things are possible. If you can share an Url to your form I can possibly improve the answer.
I`m trying to read the value from an input and fill it in one empty div.However , the value is being read but when I click the button submit , the value appears for like 0.2 seconds on the empty div , and then , disappears ... any suggestions why?
HTML :
<div id="vuvedenaSuma">
</div>
<form action="">
<input type="text" id="suma" required="required" placeholder="Въведи сума" name="Suma" />
<button id="submit">Submit!</button>
</form>
Javascript:
function valueRead(){
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
}
document.getElementById('submit').addEventListener('click',valueRead);
I want to make it withe eventListener , not onclick attribute on the button.
Your form is being submitted right after the execution of the function.
You can prevent the default event(form submission) to be called with event.preventDefault() like this:
function valueRead(e){
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
e.preventDefault();
}
https://jsfiddle.net/ez0qchyq/
Your event is firing, then the page is likely reloading because of the form firing. Try using
event.preventDefault()
and it will prevent the form from submitting.
Edit: Also, the comment below me is absolutely correct. Remember to pass the event into the function.
The default way that a form "submits" is to send a new page request to the server, using the given inputs as parameters. From there, a serverside language like PHP might save them. Often, this would churn out an "Operation successful!" page or similar.
In your case, your form's action is blank, meaning it will "submit" to the page it's on. Since your page is pretty basic, it will reload without any of the sent information appearing in it.
As John Kossa suggested, you could intercept this by adding an argument, let's say, "evt", to the parentheses of the valueRead function, and then calling evt.preventDefault().
When you click the button then you send the form and the page is automatically refreshed. To prevent this behavior try this solution
function valueRead(e){
e.preventDefault();
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
}
Also, you might want to use the event listener on submit:
document.getElementById('formName').addEventListener('submit', valueRead);
I am currently viewing all the possibilities for preventing multiple submission with button tag. The problem I am facing is that if users click submit button really fast it will enable them to submit multiple posts. I would like to restrict the submission to just one submission. I tried to use onclick="this.disabled = true, but it makes the button not working at all. The current button tag looks like this:
return "<button class='button btn btn-primary' id='gform_submit_button' onclick='this.disabled = true' type='submit'><span>Submit!/span></button>";
Can anyone guide me as to how to achieve this?
Ultimately, you cannot prevent multiple submissions on the client-side. You would have to implement these security measures on the server-side, in whatever server-side language you are using (e.g., PHP).
On the client side, you could do something like this
var canSubmit = true;
$('.button').click(function(){
if(canSubmit)
{
// fire missiles
canSubmit = false;
}
else
{
// sorry missiles loading
}
});
Now since after clicking once canSubmit has been set to false, a second click would not run the code. After validating or processing your submitted data you can set canSubmit back to true.
When the button is onClicked call this function:
function submitFunc(formId){. document.getElementById(formId).submit();
}
Submitting a page is always going to be tricky. There are two challenges with submit
As you rightly mentioned that user can submit same page multiple times
After submitting page if user refresh the page then also page is going to be resubmitted
There is one trick to handle this challenge redirect the page with GET call. The GET call which you have used to load the data. Read more about it here.
So I would recommend to redirect page to GET once form is submitted.
In this process the new form will be loaded and if user try to submit the form validations will be fired that will handle 1st challenge.
And due to redirect as your last call is GET on refresh data will be loaded and there is no harm in it.
I have a form with a submit button and it works fine, but I now have a user request to make the form get saved (posted to save action) if a link on the page is clicked and the form is "dirty".
I've got the logic in place by having an isDirty JavaScript variable, now I would like to post the form from the JavaScript function when it is dirty.
My form declaration is as follows:
<form id="formSmart" action="<%= ResolveUrl("~/SmartForm/Proceed") %>"
method="post" enctype="multipart/form-data">
and my JavaScript is:
function checkLink() {
if (isDirty) {
$("#formSmart").submit();
}
}
The proceed action doesn't get called, yet when I click the submit button on the form it works fine. What am I doing wrong in the JavaScript?
Note: The call to checkLink() works fine, the ultimate problem is that $("#formSmart").submit(); is not posting to the Proceed action.
You have the correct way of submitting the form based on what you have posted and the names match up.
Are you sure you are calling checkLink and is isDirty equal to true?
Put and alert('Test'); right before you submit and in the if scope.
EDIT: To hookup your event you need to do the following:
$('#yourLinkID').click(checkLink(); return false;);
Note the return false which will cause your link to not execute a navigate. If you want the link to navigate, you can just remove that part.
Sounds like the requirement is that 'a link on the page is clicked'.
Perhaps attach this event to all the <a> tags on the page.
$(document).ready(function() {
// all <a> tags get the checkLink attached to them
$("a").click(checkLink());
});
your problem is that the browser navigate before the page performs your submit.
the solution is suspending the navigation till you save the form.
The UGLY solution:
you could do it buy saving the clicked url at a hidden field,
returning false to stop the navigation,
and after submit check for a value there and if it exists do navigation
A better solution:
post the form via ajax and after the ajax call completes(no need to check for success or error) perform the navigation(to make it really easy just use ajaxForm ajaxForm plugin)
the only problem with this solution is if the link has target="_blank" because then you have to use window.open which might be blocked by popup blockers
you can play with a simple jsbin sample i prepared showing this
this example post some values to an older version of this page + navigate to google, open fiddler and see that it first post and then navigate.
If you went to the jsbin page stop reading here
here is the Html:
<form id="formSmart" action="http://jsbin.com/oletu4/edit" method="post">
<input type="text" name="someLie" />
<input type="text" name="someLie2" />
<input type="submit" value="submit" />
<a id="lnkNavOut" href="http://www.google.com">www.google.com</a>
here is the JS:
$(document).ready(function(){
$("#lnkNavOut").click(function(){
var jqFormSmart = $("#formSmart");
//check here if the form is dirty and needs to be saved
var jqClickedLink = $(this);
$.ajax({
url: jqFormSmart.attr("action"),
type: "POST",
data:jqFormSmart.serialize(),
complete:function(){
location = jqClickedLink.attr("href");
}
});
return false;//stop navigation
});
});