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.
Related
One is a small code that allows me to view error messages when the form fields are empty or when everything is fine. What I would like to do is enter a loader or text to indicate that the submitted action is being processed. I really don't know where to start, can someone help me understand how to achieve this?
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
jQuery.post(
$form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.newdiv').html(data);
}, 'json',
);
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
});
});
});
Firstly put the loader in your HTML file where you want to display it. i.e: below the submit button
<img
src="https://thumbs.gfycat.com/PessimisticGlamorousDunnart-size_restricted.gif"
class="loader"
alt="Loader"
height=25
width=25
>
Then add CSS for this loader:
.loader{
display:none;
}
Then put the below code in jQuery:
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "your_url",
data: $(".mts-edit-account").serialize(),
beforeSend: function() {
$(".loader").show();
},
success: function(msg) {
$(".loader").hide();
}
});
});
});
AJAX requests using jQuery allows you to handle request completion, failure or success using the returned value from ajax() function. In your case you need to start by showing the loader before starting the request, then hide on completion. To do that, you can use always() function. That will make sure it's always called in case of success or failure.
// Show loader
jQuery.ajax({
// ..
}).always(() => {
// Hide loader
});
I have an issue, do not know if it possible or not, how to check if my container is already loaded or not, because sometimes it is being loaded faster, sometimes slower and if it does not succeed in time getting an error in javaScript where gridview some functions are not recognizable(because the gridview is not loaded fast enough). Hope it is clear. Thanks for Your time.
Code:
function LoadPartial(partialUrl, container) {
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
}
});
//.done(function () {
// return;
//});
}
you can use something like this.
$(".container").load(function (){
alert("Loaded :)");
});
Let me know in-case this doesn't work.
You can try using .data()
if ($('#mycontainer').data('loaded')) {
// your code
}
If you mean to find event when data received use "complete" function:
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
},
complete: function() {
console.log('container filled with data');
}
});
I created a form on /contact-us and having action="/contact-us". Now, when I added Ajax to it, it is sending the request three times, i cannot find the reason.
Ajax:
define(['jquery', 'foundation.alert'], function($) {
return {
init: function() {
$("#success-alert").hide();
$("#error-alert").hide();
$('button').click(function(e){
$('input').map(function() {
if(!$(this).val()) {
$("#error-alert").show();
$("#success-alert").hide();
return false;
} else {
$('document').ready(function() {
var form = $('#contact_us'); // contact form
var submit = $('button'); // submit button
var status = $('#form-status'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '/contact-us', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
submit.html('Sending....'); // change submit button text
},
success: function(data) {
form.trigger('reset'); // reset form
$("#success-alert").show();
$("#error-alert").hide();
submit.html('Send'); // reset submit button text
},
error: function(e) {
console.log(e);
}
});
});
});
}
});
});
}
}
});
You are looping through all the inputs and applying on submit for every input in your form. So if it is submitting 3 times, you must have three inputs. Each time you click the button, you will be adding even more submit handlers! The whole design of this is wrong.
You should not be attaching the submit handler inside of the click event, it should be outside and have it done one time. Do your validation inside of the submit handler to make sure that it is valid before making the Ajax call.
try this solution.
var wait = false;
wait variable for global scope
if (!wait) {
wait = true;
$.ajax({
url: '/contact-us', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function () {
submit.html('Sending....'); // change submit button text
},
success: function (data) {
wait = false;
form.trigger('reset'); // reset form
$("#success-alert").show();
$("#error-alert").hide();
submit.html('Send'); // reset submit button text
},
error: function (e) {
console.log(e)
}
});
}
After going through my code i realized what mistakes i have been doing and also realized that reading code is more important than writing it.
This is how i rewrite the code and its working fine but i am still not sure if it is the best approach.
define(['jquery', 'foundation.alert'], function($) {
return {
init: function() {
$("#success-alert").hide();
$("#error-alert").hide();
$(function () {
$('#contact_us').on('submit', function (e) {
$.ajax({
type: 'post',
url: '/contact-us',
data: $('#contact_us').serialize(),
success: function () {
$("#success-alert").show();
$("#error-alert").hide();
}
});
e.preventDefault();
});
});
$('button').click(function(e){
$('input').map(function() {
if(!$(this).val()) {
$("#error-alert").show();
$("#success-alert").hide();
return false;
}
});
});
}
}
});
Note: Never take writing code as a burden.
The error in the title of the post came from jQuery version 1.10.2, line 637
I've got a modal that pops up on a button click with some textboxes and when a button inside the modal is clicked, the information that's in the text boxes is added to a database via AJAX. In order to make the page a little more user-friendly I added a setTimeout function to pause the hiding of the modal so the user can see a verification message that the data was added to the database. Block 1 of my code adds the record to the database, but the setTimeout call doesn't work right:
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
//something about the setTimeout function
//that gives the error in the title
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
//*******this function doesn't run
window.setTimeout(function () {
$('#contact').modal('hide');
$('.modal-body input').each(function () {
$(this).val('');
}, 1000);
});
}
});
}
I fixed it using the code:
(the success function is what we need to pay attention to here)
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
});
}
I see that I in the first block I didn't close the each function, and I fixed that in the second block and that's why it works, but for future reference, what does this error really MEAN in this context?
It means that you left off the second argument to setTimeout and instead passed it as the second argument to .each().
edit — it looks like jQuery is picking up the argument (that 1000) and trying to pass it through to its internal each implementation. The .apply() function expects it to be an array.
I have a link 'hrefs="javascript:callFunc()">' that invokes the function 'callFunc()';
function callFunc(){
$.ajax({
type: "POST",
url: "call.php",
data: "i="+i+add,
success: function(msg){
$('#content').html(msg);
}
});
}
The issue: When the user click's that link 4 times, the callFunc is going to invoke 4 times, sending 4* the post via ajax.
Anyway to lock this down?
*Beaware that the link could be through out the page too; And there could be similar functions.
What about:
window.funcRunning = false;
function callFunc(){
if(window.funcRunning == false) {
window.funcRunning = true;
$.ajax({
type: "POST",
url: "call.php",
data: "i="+i+add,
success: function(msg){
$('#content').html(msg);
window.funcRunning = false;
}
});
}
}
Have the event handler disable the link, or ever better replace it with "Please wait…" or other appropriate feedback message.