jQuery form submit, prevent from sending multiple times after first submit - javascript

I am making a webapplication that uses a jquery submit to request some data, but i don't want people submit the form multiple times after they submit the first time. So i want after a submit, that the next submit does nothing for a few seconds.
$("#updatestock_form").submit(function(e){
// requesting my data..
});
How can i achieve this?

"So i want after a submit, that the next submit does nothing for a few seconds."
If you mean that you want the user's second and subsequent submit attempts to be ignored until after a certain number of seconds you can do that in a number of ways. Here's the first that came to mind:
var allowSubmit = true;
$("#updatestock_form").submit(function(e){
if (!allowSubmit) return false;
allowSubmit = false;
setTimeout(function(){ allowSubmit = true; }, 5000);
// your existing submit code here
// requesting my data..
});
That is, have a flag that indicates whether submit is currently allowed. On the submit event if that flag is false just return false immediately to cancel the submit event. Otherwise (if it is currently true) set the flag to false, set a timeout to change the flag back after, say, 5 seconds, and then carry on with your existing submit code.

$("#updatestock_form").submit(function(e){
$(this).unbind("submit")
$("#submitButton").attr("disabled", "disabled")
});
Very simple.

You are doing an ajax-request to submit? So create some locking variable var locked;and set it to locked = true; when submitting and reset it to false when the ajax call is finished. (sucess-condition)

Disable button on onclick event of button
$("#buttonId").bind('click', function() { $(this).attr("disabled", "disabled"); });
and remove disabled attribute after successful operation

Related

How to distinguish between a successful and a failed submit in JQuery?

I'm working in a legacy ASP.NET/MVC project that is using a bit of jQuery to provide an unsaved changes warning. There's a utils.js file that's included on every page that contains:
// Has the user made changes on the form?
var formHasModifications = false;
$(document).ready(function () {
// We want to trigger the unchanged dialog, if the user has changed any fields and hasn't saved
$(window).bind('beforeunload', function () {
if (formHasModifications) {
return "You haven't saved your changes.";
}
});
// If a field changes, the user has made changes
$("form:not(.noprompt)").change(function (event) {
formHasModifications = true;
});
// If the form submits, the changes are saved
$("form:not(.noprompt)").submit(function (event) {
formHasModifications = false;
});
// $(document).ready() may make changes to fields, so we need to clear the flag
// immediately after it returns
setTimeout(function() {
formHasModifications = false;
}, 1);
});
The problem? The .submit() event fires, and is caught, on every submit - including on submits that don't actually submit the data.
That is, if there is a validation error, clicking on the submit button leaves the user on the page, with unsaved changes, and displayed validation failure messages, but it also clears the formHasModifications flag.
The result is that if the user makes changes to one or more inputs, clicks "submit", gets validation errors, then navigates to a different page without fixing them, and resubmitting, they do not see the unsaved changes dialog, even though they do have unsaved changes.
This is, as I said, a legacy app, and I'm not interested in making fundamental structural changes. But if there's some way of being able to tell, in jQuery, whether a submit event succeeded or failed, I'd really like to know.
OK, as Terry pointed out, it depends upon what we're using for validation.
In our case, we're using jquery.validate. And with this, we can call .valid() on the form to determine whether the form passed validation:
// If the form successfully submits, the changes are saved
$("form:not(.noprompt)").submit(function (event) {
if ($(this).valid()) {
formHasModifications = false;
}
});

Avoid multiple form submit in html

I'm facing a sort of dummy problem.
On my site there is an order form (simple html form) and I noticed that I get double commands from time to time.
I realized that if I clicked repeatedly few times the submit button (before the action page is loaded) I got as many commands as I have clicked.
So I wonder if there are simple solution to make form submission asyncronous?
Thanks
P.S. I added JQuery UI dialog on submit "wait please..." but I get still double commands.
UPDATE
As GeoffAtkins proposed I will:
disable submit after dialog is shown
make use of unique form's token (as it is already added by Symfony) Do not use Symfony token as unique form token as it is always the same for current session. Use just random or something like that.
I would consider doing this (jQuery since you said you used that)
$(function() {
$("#formId").on("submit",function() {
$("#submitBut").hide();
$("#pleaseWait").show();
});
});
if you submit the form and reload the page.
If you Ajax the order, then do
$(function() {
$("#formId").on("submit",function(e) {
e.preventDefault();
var $theForm = $(this);
$("#submitBut").hide();
$("#pleaseWait").show();
$.post($(this).attr("action"),$(this).serialize(),function() {
$theForm.reset();
$("#submitBut").show(); // assuming you want the user to order more stuff
$("#pleaseWait").hide();
});
});
});
NOTE that disabling the submit button on click of the submit button may stop the submission all together (at least in Chrome): https://jsfiddle.net/mplungjan/xc6uc46m/
Just disable the button on click, something like:
$("#my-button-id").on("click", function() {
$(this).attr("disabled", "disabled");
});
var bool = true;
function onclick()
{
if(bool)
{
//do stuff
bool = false;
}
else
{
//ignore
}
}
You could disable the button on the form when it is clicked, and then continue to perform the action. You would probably change the text to say "loading..." or some such.
You may also want to re-enable the button on fail or complete of the ajax request.
I've done this many times similar to this: https://stackoverflow.com/a/19220576/89211

Aweber form not collecting leads because of simple jquery code [duplicate]

I have a form that uploads a file and targets an iframe on the page. When the user clicks submit, I want the file contents to "clear" out.
I tried this
$('#imageaddform').submit(function(){
$('#imagefile').val('');
});
But it clears the form before the submit, so nothing is ever uploaded.
Is how do I clear after submit?
If you have no other handlers bound, you could do something like this:
$('#imageaddform').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
$('#imagefile').val(''); // blank the input
});
Lonesomeday's solution worked for me but for Google Chrome I found it would still submit empty form data unless I added a timeout like this:
$('#imageaddform').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
setTimeout(function(){ // Delay for Chrome
$('#imagefile').val(''); // blank the input
}, 100);
});
You could do something like this:
$('#imageaddform').submit(function(){
setTimeout(function() {
$('#imagefile').val('');
},100);
});
How are u submitting the form? if this is normal form post then then page wont exist in that case i am wondering if u are looking to clear the form before the page refreshses so that when the user comes back he doesn't see the values populated.
If the form is submitted by ajax then you can
function(){
$('form1')[0].submit();
clearForm();
}
Did i miss the question?

On submitting a form, check for a value that, if present, opos up a modal window for more info

I have a form that uses jQuery Validate. You click the Submit button, form gets validated and submitted via ajax. I want to add a step to this process.
I want to check for the presence of a value, say x. If x is NOT in the form I want to go ahead and submit it as I already do. If it IS in the form I want to open a modal window that requests further info THEN submits the form with that extra info added into the request.
Currently I can get the modal to trigger but then the form just continues with the submission. How do I get the form submission to pause while the modal is dealt with by the user?
jQuery Validate has a "success" option that is called after successful validation (which is when I want to check for triggering the modal) but that still doesn't pause execution.
In a nutshell: How do I validate a submitted form, check if the value x is present, if it is not present submit the form but if it is present pause the submission, pop up a modal window, let the user fill in some more data (and presumably click a "done" or "cancel" button of some sort), add that to the collected form data and then submit the lot? The pausing submission part has me stumped.
Use submit() on the first form...
$('#form1').submit(function() {
// The below validation goes in here
});
Validate it...
$("#form1").validate({
// Whatever rules you want to validate by
});
Check if the form is valid...
if($('#form1').valid()) {
// Branching on x, example below, will go in here
} else {
// It's not valid, stop the submission
return false;
}
Branch on x. If present, open the modal, if not return true to submit the form as is
if (x !== undefined) {
// Here is where you also need to pass the other form data to the modal
// append hidden text fields to the form and populate with the values
// Open your modal window, then stop the default submit process
$('#themodalwindow').openModal();
return false;
} else {
// No x so submit the form as is
return true;
}
Now you have to submit the form in the modal...
$('#form2').submit(function() {
return true;
});
If you appended the data collected in form1 to form2 then submitting the form will include everything you need. BTW, you can cache some stuff in that but this is the gist of it.
You can't pause a form submit, but you can cancel it if you return false on the form's onsubmit event. After you get your additional data from the modal window, simply add the data to the form and resubmit it via javascript.
Hook onto the form's submit function:
$('form').submit(function() {
if (x !== undefined) {
$('#dialog').show();
return false;
}
});

jQuery Forms - Ajax and normal submit the same form

I have a confirm step in one of my pages.
Desired action:
user clicks 'submit' and an AJAX request is made that does the appropriate action and returns a confirm dialog
user 'confirms' and then the form is submitted using a standard post.
So for the first part I'm fine using the jQuery form plugin:
$('form').ajaxForm(...options...);
For the second part I'd like to submit the form again, but non-ajax. Basically I want to do this:
$('form').submit();
And have it do an actual browser post. The problem is that $('form').submit() just triggers the ajax submit.
Is there a way to use the form for both purposes?
$('forms-submit-button').click()
..does that work , for the second submit?
:) :)
Can't you just unregister the submit event handler after you've ajax-posted the results? Why do you need to post the same data twice, by the way? If the data haven't changed between the Ajax post and the regular one, why is the regular one needed?
You can try to change a value in the form (se some hidden value to 1), do another ajax request and finally do a redirect. It's not the same but it should work.
Note that it's very strange to submit the same data twice though..
Answered by Surya as a comment (if you check this question again please post the answer so I can mark it!)
$('forms-submit-button').click() ..does that work , for the second submit?
form onsubmit='ajaxCheck();'
...
/form
script
var ajaxCheck = function()
{
//do check
return confirm(); // if ok form submit normaly / if cancel form doesn't submit
}
/script
or something with a flag:
var flag = true;
var firstCheck = function()
{
if( flag )
{
//do the ajax Call which will fire an event,
// let's call it onData
$.post(url,{param1:val1,...,paramN:valN},onData);
return false;
}
return true;
}
var onData = function (data)
{
flag = !confirm(...);
//if user click ok and try to re-submit the form
//this time will just go
}

Categories

Resources