Prevent multiple form submission jquery - javascript

I am building a web app, I am submitting a form with jquery, if I should click on the submit button the first time, it will sub!it once, if I should click it the second time after the first form is submitted, it will submit twice, if I could click it the third time, it will submit 3 times and so on, pls how will I prevent it. Am not talking of disabling the submit button, and I also if I should reload the page if it reset the submission
$.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType });

This is a classic example. Basically, what you want to do, in your submit method, you want to disable the submit button before you call your ajax. Once the ajax is completed, you will have 2 outcomes, success, or error. In both cases, you want to enable your submit button.
function buttonSubmit() {
let buttonSelector = event.srcElement;
buttonSelector.disabled = true;
$.post({
url: "your-api",
data: {
someData: "kjfgkdjfglkdf"
},
success: function (result) {
// handle your success, do stuff
buttonSelector.disabled = false;
},
error: function (response) {
// handle your error, do stuff
buttonSelector.disabled = false;
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="buttonSubmit()">Click Me!</button>

Related

Display loading icon and then redirect to new page

Lets say I have one page "page1" which consist of some info and a button named "Add".
When I click on this button, it opens a popup modal window that consists of a form with around 10 fields and submit button. Once I click on this button, I used ajax post to submit the form and at the server side it does insert and update operation and return success or failure result.
During this ajax process, I am displaying a loading image. What I am trying is just after this loading image it should redirect to new page. Lets say "page2". But in my code, i see after this loading stops , I see the modal window and "page1" for about 2-3 seconds and then only it redirects to "page2".
I am not sure if my question is logical or not but still if there is any method to stop it.
Below I have ajax processing code.
Thank you.
$.ajax({
type: 'POST',
url: 'page2.php',
data: {
'data': form_data
},
success: function(response)
{
var arr = JSON.parse(response);
if(arr.success == true) {
window.location.href = 'page3.php';
}
else {
alert('There are some error while saving record.');
}
},
beforeSend: function()
{
$('.loader').show().delay(9000);
},
complete: function(){
$.fancybox.close();
$('.loader').hide();
}
});
$.ajax({
success: function(response)
{
...
if(arr.success == true) {
...
}
else {
...
$('.loader').hide();
}
},
...
complete: function(){
$.fancybox.close();
}
});
Don't hide the loader after ajax request is done.

Waiting for all AJAX call than show dialog box

I am working on a dynamic online form website. In the main form, I have multiple sub-forms which can be added and deleted dynamically.
<div class='subform'>
//form fields
<input ...>
...
<button class='subform_submit'>
</div>
For each subform, I bind an AJAX call on the subform's submit button like this:
$('#main').on('click', '.subform_submit', function(){
// Get this subform's user input
...
$.ajax({
url: ..,
type: ..,
data: /* this subform's data */
});
});
So in that page, I may have 0 to 10 subforms depending on the user's selection.
I also have a main submit button on the bottom of the page, which can submit those subforms and the main form's data together.
$('#main').on('click', '#submit', function(e){
$('.subform_submit').click(); // Submit each subform
bootbox.confirm({ });
})
Once main submit button is clicked, I want to show a loading picture and then show a dialog box (I use bootbox.confirm() here) until all AJAX calls have completed.
This dialog box is telling user that whole form including sub-forms has been submitted.
But the problem is that each AJAX call may take 2 seconds to complete and I don't know how may calls may be pending completion. How can I write this main submit button so that it will:
Show the loading image immediately, and
Hide the loading image and show the dialog box after all AJAX calls have completed?
Keep track of how many sub-forms there are;
$subFormsCount = $('.subform').length;
Keep track of how many forms have been submitted;
$submittedForms = 0;
Each time a form finishes submitting, add to the $submittedForms;
$.ajax({
..
..
done: function(){
$submittedForms++;
}
})
Create a global timer to see if the number of submitted forms matches the total number of subforms. If true, hide the dialog box;
setInterval(function(){
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}, 50ms)
Edit
You could skip the global timer (as this will probably be a few milliseconds out) - include the check in your ajax.done instead;
$.ajax({
..
..
done: function(){
$submittedForms++;
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}
})
You want to use .done() in order to specify code that should wait until the AJAX asynchronous function completes.
$.ajax({
url:..,
type: ..,
data: /* this subform's data*/ })
.done(function() {
//Put code here
});
Have you tried .ajaxStop() event handler ?
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
});
also, check this answer
I assume you have 9 subform and 1 main form.
Code for 8 subform will be same.
I use here async:false : Means next ajax will not be call until 1st one is not completed.
Sample Code Format :
var id = 5;
$.ajax({
url: ,
type: 'POST',
data: {'id':id},
dataType: 'JSON',
async: false,
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred!');
},
success : function(response){
}
});
Just set variable in your last sub form that is 9th subform.
success : function(response){
var counter = true;
}
if(counter){
/* Code to show dialog.*/
}
You can use $.when to wait for each request to complete. Something like this should get you close. You'd basically want to store all the ajax requests in an array and pass that to when as the arguments.
$('#main').on('click', '.subform_submit', function () {
var formRequests = $('.subform').map(function () {
var $form = $(this);
return $.ajax({
url: '',
data: $form.serialzeArray()
});
}).get();
$.when.apply(undefined, formRequests).done(function () {
console.log('All done!');
});
});
Here goes a very similar little demo I just made up: https://jsfiddle.net/g9a06y4t/

Expand div closes when pressing enter

So I have this chat,
http://codepen.io/anon/pen/Frmez
$(function() {
$('.textarea-chat').on('keyup', function(e) {
if (e.which == 13 && ! e.shiftKey) {
$(this.form).submit()
return false;
}
});
});
Updated code ^
But one problem with it is that if you input a text to send away to the chat and press enter, the chat window closes, it should stay open but I can't figure out how
$(this.form).submit()
This actually submits the <form>. You're probably getting the error "Please use POST request" because by default it uses GET. It doesn't like being sent a query string, so it gives that error. You can POST stuff to it, but nothing will happen.
In order to POST stuff to it, you need to use Ajax. See docs.
For example:
$("#myForm").submit(function () {
var url = "path/to/your/script.php"; //handle form input by your script
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), //serializes the forms elements
success: function (data) {
alert(data); //show response
}
});
return false; //avoid executing actual submit of the form
});

make sure ajax request doesn't get fired multiple time

I was working on a simple form page and I was wondering what happens if someone clicks the submit button many many times (incase my shared hosting somehow seems to be slow at that time).
Also, incase anyone wants to look at my code
$.ajax({
url: "submit.php",
type: 'POST',
data: form,
success: function (msg) {
$(".ressult").html("Thank You!");
},
error: function () {
$(".result").html("Error");
}
});
Is there a way to make it so after the user clicks it once, it won't run it again until the first click is done?
Thank you
You can use jQuery's .one() function:
(function handleSubmit() {
$('#submitBtn').one('click', function() {
var $result = $('.result');
$.ajax({
url: 'submit.php',
type: 'POST',
data: form,
success: function (msg) {
$result.html('Thank You!');
handleSubmit(); // re-bind once.
},
error: function () {
$result.html('Error');
}
}); // End ajax()
}); // End one(click)
}()); // End self-invoked handleSubmit()
*Edit: * Added recursion for multiple submissions.
Use a boolean flag
if (window.isRunning) return;
window.isRunning = true;
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete : function () {
window.isRunning = false;
}
});
var $button = $(this);
$button.prop('disabled', true); // disable the button
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete: function() {
$button.prop('disabled', false); // enable it again
}
});
Have you considered replacing your submit button with a loader image while the query executes, then re-adding it once the query is complete?
EDIT: Using the loader image is a sort of universal "I'm doing something" indicator, but disabling the button would work too!
You could disable the submit button, before the ajax call is made. And then, if required, enable it on success.

event.preventDefault not working

I have this simple code here, nothing too advanced.
$("input#send").submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
});
Whever I click on the "send" button, the event.preventDefault function doesn't work, and the page loads.
Any ideas why?
A form has the submit event, not a button. Plus, an ID should be unique so tag#id can just be #id.
$("#theform").submit(function(event) {
event.preventDefault();
// ...
});
You need to bind to the form's submit event or to the button's click event and call event.preventDefault() if you want to stop the form from submitting:
$('form').bind('submit', function (event) {
event.preventDefault();
});
$('form').find(':submit').bind('click', function (event) {
event.preventDefault();
});
I believe the submit event is for the form element. For an input[type='button'] you might want to use the click event.
Add quotes around 'add.php'
Change the selector in the first line to the id attribute of the form which contains input#send.
The advantage of handling the submit() handler on the form rather than the click handler on the input is that some forms can be submitted by pressing the enter key (when the user is focused on one of the form fields). If you don't have an id attribute, add one or use a different jQuery selector to target the form tag.
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: data,
success: success,
dataType: dataType
});
return false;
});
Try using return false instead
$("input#send").submit(function(event) {
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false;
});
If you're using preventDefault I assume that means you do NOT want the default submit action. I would just use a different event instead of using .submit. To me, it's not the submit action that you want to intercept, but rather the click that would normally cause the submit.
$('#inputSend').on('click', function(event) {
event.preventDefault();
//the rest
});
If both return false and event.stopPropagation() don't work, try the following method. Using .on() will make the submit function accessible. Once you change the .submit() to .on("submit"..), you can either use return false or e.stopPropagation().
$(document).on("submit", "input#send", function(event) {
event.stopPropagation();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false; });

Categories

Resources