prevent multiple submission with button - javascript

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.

Related

Multiple forms with one button for 2 different functions [duplicate]

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.

how to run jquery code after hml form submission

this is my javascript code :
<script type="text/javascript">
$(document).ready(function(){
$('#saveBtn').click(function(){
var prenom_length = $('#form_prenom').val().length;
if (prenom_length<5) {
$('#prenom_error').html("please enter an other name");
}
});
});
</script>
the jquery code is working few seconds after form submission the displays the error text just before the page reloads but after reloading the page it disappears , i want it to keep the same text even after the page refresh how to do ?
If I understand you correctly, you want to show an error message after someone submits the form so that they know they should correct it. By default if you press a submit button in an HTML form the browser wil send the request to the server and the server will give the user a new page.
You want to prevent that last bit from happening. The browser should execute your jQuery and if you find an error in the form you want to prevent that default submit to the server from happening. As it happens (pun intended) jQuery can do exactly that, check out the documentation here.

How to setup event tracking on Google Analytics on form submission?

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.

Javascript code not running after the page is refreshed or reloaded

I have a javascript code that, whenever a checkbox is checked, will reload my current page and then is supposed to grey out some input fields.
However, it is only doing the reload when the page is reloaded the input fields are never greyed out.
$(document).ready(function(){
$("#storePickUp").on("click", function () {
if ($(this).is(":checked")) {
document.getElementById("shippingForm").submit();
document.getElementById("shippingAdress").disabled = true;
document.getElementById("shippingState").disabled = true;
document.getElementById("shippingCity").disabled = true;
document.getElementById("shippingZip").disabled = true;
document.getElementById("shippingZipCode").disabled = true;
document.getElementById("shippingButton").disabled = true;
}
});
});
So in your code on the 4th line where you call .submit()... unless you have some extra magic on the page that you are not showing, this line will proceed to post/get your form to whatever url you have configured in that form.
What this means is that the lines underneath that do not matter at all, since they will not be executed on the forms target page.
To get around this if you truly need the form post in the middle, you would need to post to a specific url and use that url as a trigger on page load to disable those elements. Not directly after the click, but rather on the newly loaded page that is the target of the form... make sense?
I think that's because it's only disabling them when you click on #storePickUp but if your page is reloaded it will reset.
Method submit is executed, page reloads, code after submit is never executed. Even if that code would be executed, page refresh nullifies any changes.
You should probably do submitting with ajax, not with submit method. If you are using jQuery, it will make it easy for you:
http://api.jquery.com/category/ajax/

redirecting to next page

I wrote a javascript function to go to a particular page if it came from a particular page.
Function:
function proceed()
{
if( document.referer == "http://abcd.com/index.php?action=SignUp")
{
return document.location.href = "http://abcd.com/editprofile.php?action=editprofile";
}
}
Submit button for a form in current page(b):
What i want is to go through a sequence of pages a->b->c , where a is previous , b is current , and c is next in my case. b has a form, on submitting values to the form, it should also call the javascript function and then go to the page c.
Can anybody help me find out where is the mistake? Any help would be highly appreciated. Thanks.
Since you have a form I guess there's also some php/cgi script that will handle the form's data!?
In that case your form won't continue to that script if you override your submit button via javascript in such way that it loads another page (other cases like validation do work that way, of course).
So
Your submit button has spaces next to the onclick attribute: onclick = "javascript... should be onclick="javascript....
Your function proceed() should return true for the submit to perform.
Even after all syntax correction, there's still something odd. After all, you can only give one "next page" functionality to your submit button. So what should the form call:
your php or cgi script? Then you can build a redirect to page "c" into that one.
your page "c"? Then what do you need the form for?
both, but independently? In that case I suggest a javascript popup from proceed() displaying page "c" and returning true so the form continues with its script.
To be more accurate you will have to provide more of your application's code.
Solution seems to be the following. Use the submit attribute for your button:
<button type="button" onclick="proceed(); alert('You are not authorized to execute this action!');">Click Me!</button

Categories