AJAX sending multiple requests after button click - javascript

I just want one click to equal one submit in my jQuery code.
I've read quite a few posts on this same topic but I think mine is different. I do have a mouseleave and focusout event that I'm using to find errors in user input. Those functions feed down into the function that is submitting multiple times. The more times I hit mouseleave and focusout the more times my Ajax request is submitted. But I need mouseleave and focusout to continue to work and check the users input, that's why I'm not using one. Please see my code below, the function that I think is submitting multiple times is handleButtonClicksAfterError
function getCreditAmountToSend(modal){
console.log("getCreditAmountToSend");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
checkBox.change(function(){
if($(checkBox).is(":checked")) {
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('amountToSend', creditAmount);
}
});
var pendingCreditAmount = $(modal).contents().find("#pending_credit_amount");
pendingCreditAmount.on({
mouseleave: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
},
focusout: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
}
});
}
function adminForGetPendingCredit(modal){
console.log("adminForGetPendingCredit");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
if(!$(checkBox).is(":checked")) {
var enteredAmount = +($(modal).contents().find("#pending_credit_amount").val());
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('enteredAmount', enteredAmount);
doWeDisplayError(modal,creditAmount, enteredAmount);
}
}
function doWeDisplayError(modal,creditAmount, enteredAmount){
console.log("doWeDisplayError");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", false);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", false);
if(creditAmount < enteredAmount){
$(modal).contents().find("#pending_credit_amount").val("");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", true);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", true);
displayError();
}
else{
handleButtonClicksAfterError(modal, enteredAmount);
}
}
function handleButtonClicksAfterError(modal, enteredAmount){
// this is the problem!!!!!!!!!!!!!
console.log("handleButtonClicksAfterError");
sessionStorage.setItem('amountToSend', enteredAmount);
var continueButton = $(modal).contents().find("#fresh-credit-continue-shopping");
continueButton.click(function() {
modal.hide();
});
var checkoutButton = $(modal).contents().find("#fresh-credit-checkout");
checkoutButton.click(function() {
console.log("handleButtonClicksAfterError");
sendData();
});
}
function displayError(){
console.log("displayError");
$(function(){
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr("placeholder", "Whoops, that was too much");
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr({
class: "form-control form-control-red"
});
sessionStorage.removeItem('enteredAmount');
});
}
This is the function that actually POSTs the data
function sendData(){
var amountToSend = sessionStorage.getItem("amountToSend");
var products = $.parseJSON(sessionStorage.getItem("products"));
console.log("sendData");
console.log("This is the amount to send " + amountToSend);
$.ajax({
url: "/apps/proxy/return_draft_order",
data: {amountToSend, products},
type: "POST",
dataType: "json",
complete: function(data) {
window.location.href = data.responseText;
console.log("This is the URL from poll " + data.responseText );
return false;
},
});
}

It ended up being super simple.. I just needed the jQuery off method.. I attached it to the button before click and everything is peachy.. Looks like this:
checkoutButton.off().click(function(){});
off clears all the previous event handlers and then just proceeds with Click
Pretty cool, to read more check it out here

use async:false to prevent multiple request
$(document).off('click').on('click', function(){
$.ajax({
type:'POST',
url: ,
async:false,
cache: false,
data:{}
,
success: function(data){
},
error:function(data){
}
});
});

Related

How remove submit button and automatically load model box

I just need remove submit button and open model box without submit button, i checked the code but it's little big script I'm confused what i do. I can use onload Event?. The script is an indian payment gateway service(Razorpay). I try to modify it's not working, I need the exact way. I'm new in JS. I don't know where i can modify with onload event?
This is my JS script:
jQuery(document).ready(function($){
function showModal(response) {
$('#response').html(response);
$('html, body').css('overflow', 'hidden');
$('.modal-container').show().prop('offsetHeight');
$('.modal-container').addClass('shown');
}
function hideModal() {
$('html, body').css('overflow', '');
$('.modal-container').removeClass('shown');
setTimeout(function() {
$('.modal-container').hide();
}, 300)
document.getElementById("btn-razorpay").disabled = false;
}
$('.close').click(hideModal);
// global method
function createOrder(){
$.ajax({
url: "#redirectUrl#?action=create_order&page_id=#pageID#",
type: 'GET',
success: function(order) {
if (order.hasOwnProperty('error')){
showModal(order['error']);
}
else{
order.handler = function(payment){
$('#razorpay_payment_id').val(payment.razorpay_payment_id);
$('#razorpay_signature').val(payment.razorpay_signature);
var form_data = $('form').serializeArray();
$.ajax({
url: "#redirectUrl#",
data: form_data,
type: 'POST',
success: function(response){
showModal(response);
}
});
};
}
// On dismissing the popup, enable the button again
order.modal = {
ondismiss: function(){
document.getElementById("btn-razorpay").disabled = false;
}
};
// After order is created, open checkout
openCheckout(order);
}
})
}
// global method
function openCheckout(order) {
var razorpayCheckout = new Razorpay(order);
razorpayCheckout.open();
}
function disableRzpButton(){
document.getElementById("btn-razorpay").disabled = true;
}
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on' + evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
addEvent(document.getElementById("btn-razorpay"), 'click', createOrder);
addEvent(document.getElementById("btn-razorpay"), 'click', disableRzpButton);
})
To your submit button you need to add an event clicker which will call the showModal function.
<div id="submit" onclick="showModal()">Submit</div>
Maybe, something like this. This is assuming you have that script included in your HTML code.

how restart Jquery function if not complete

How can I let my form alert re-start once the user re-click the button if the input still empty
What I made :
after the click it will check if the inputs empty will stop the code and show alert. but once the alert appeared if I re-click the button again its not work again!
$(document).ready(function(){
function requierd()
{
$('#allrequierd').addClass("animated");
$('#allrequierd').addClass("shake");
$('#alertDanger').removeClass("hide");
setTimeout( "$('#alertDanger').fadeOut();", 4000);
}
function pass()
{
$('#alertDanger').addClass("hide");
$('#alertsuccess').removeClass ("hide");
$('#visitorFullName').val('');
$('#visitorPhoneNumber').val('');
$('#visitorEmail').val('');
$('#visitorMsg').val('');
$('#alertsuccess').addClass ("animated");
$('#alertsuccess').addClass ("bounceIn");
setTimeout( "$('#alertsuccess').fadeOut();", 4000);
}
$('#sendContactMsg').click(function ()
{
var visitorFullName = $('#visitorFullName').val();
var visitorPhoneNumber = $('#visitorPhoneNumber').val();
var visitorEmail = $('#visitorEmail').val();
var visitorMsg = $('#visitorMsg').val();
var visitorCallMethod = $('#visitorCallMethod').val();
var dataString = 'visitorFullName='+visitorFullName+'&visitorPhoneNumber='+visitorPhoneNumber+'&visitorEmail='+visitorEmail+'&visitorMsg='+visitorMsg+'&visitorCallMethod='+visitorCallMethod;
if(visitorFullName==''||visitorPhoneNumber==''||visitorEmail==''||visitorMsg=='')
{
requierd();
}else{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "functions/sContactus.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
if (result == "Success") {
// alert("DONE");
pass();
}else {
alert("Sorry Try Again")
}
}
});
}
return (start);
});
// END jquery
});
When you fire the alert the first time, your #alertDanger is getting the .fadeOut() which will apply inline display:none style to that element. You're not removing that inline style at any point, and in fact you're also not adding back the "hide" class either, so your #alertDanger will remain hidden.
What you should do is "reset" the alert div after you fade it out:
function removeAlert() {
$('#alertDanger').fadeOut();
$('#alertDanger').addClass("hide").css("display","block");
}
And in your required() function:
setTimeout( removeAlert, 4000);

How to hide a div after complete the ajax call,my code is given below ..in this code div hide before the refresh

How to hide a div after complete the ajax call,my code is given below... in this code div hide before the refresh
$(document).ready(function() {
$('#search-button').click(function() {
$('#imgLoader').show();
var request = $.ajax({
type: "GET",
url: 'response.php',
data: $('#search-form').serialize(),
success: function(response) {
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart');
$('#refcart').load(url + ' #shoppingCart');
$('#imgLoader').hide();
}
})
});
});
image loader hide before complete the refresh of two divs. Please help me
Take a look at http://api.jquery.com/load/
You can add a callback to the .load methods that will trigger once the element is fully loaded.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
In your case, something like that:
$('#my_cart').load(url + ' #mycart', function () {
$('#imgLoader').hide();
);
A possible solution could be by using the complete parameter of load:
success: function(response) {
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart', function() {
$('#refcart').load(url + ' #shoppingCart', function() {
$('#imgLoader').hide();
});
});
}
Keep in mind, thats not the best solution, because the second load will be executed not until the completion of the first.
Edit:
I would suggest you to work with tokens:
success: function(response) {
var myCartLoaded = false;
var refCartLoaded = false;
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart', function() {
myCartLoaded = true;
if(refCartLoaded) {
$('#imgLoader').hide();
myCartLoaded = false;
refCartLoaded = false;
}
});
$('#refcart').load(url + ' #shoppingCart', function() {
refCartLoaded = true;
if(myCartLoaded) {
$('#imgLoader').hide();
myCartLoaded = false;
refCartLoaded = false;
}
});
}
This way both load-functions will start at the same time and the one which stops last will trigger to hide your imageLoader.
You have more than one error in your code :
You make an ajax request to get search result, but you don't use the
response inside the success function. $().load is async, that
means you should wait the end of each $().load request before
hiding #imgLoader
The $().load is working like this
.load( url [, data ] [, complete ] )
And you should use promises to make it work.
$(document).ready(function() {
$('#search-button').click(function() {
$('#imgLoader').show();
// create the deffered instances
var myCartDeferred = $.Deferred();
var refCartDeffered = $.Deferred();
// $.ajax also return a deffered
var request = $.ajax({
type: "GET",
url: 'response.php',
data: $('#search-form').serialize(),
success: function(response) {
var url = 'detail_page.php';
$('#imgLoader').hide();
}
})
// Setup the chain of events
$.when(myCartDeferred, refCartDefferd, request).then(function() {
alert('done');
});
// start the load actions at the same time than the $.ajax and pass the deferred.resolve as complete param
$('#my_cart').load(url + ' #mycart', myCartDeferred.resolve);
$('#refcart').load(url + ' #shoppingCart', refCartDeffered.resolve);
});
});
jQuery .load returns jquery object making it inconvenient to wait for multiple loads to happen. You could add custom promiseToLoad method that returns a promise.
NB! Haven't tested this code.
$.fn.promiseToLoad = function(url, data) {
var dfd = $.Deferred(),
jquery = this;
jquery.load(url, data, function() {
if(dfd.state() === 'pending') {
dfd.resolveWith(jquery, jquery);
}
});
return dfd.promise();
}
and then
var myCart = $('#my_cart').promiseToLoad(url + ' #mycart'),
refCart = $('#refcart').promiseToLoad(url + ' #shoppingCart');
$.when(myCart, refCart).then(function() {
$('#imgLoader').hide();
});

Javascript/jQuery wait for variable true

I have the following setup:
A document can have multiple forms.
When the input on an input field changes, jQuery will fire an ajax event. And input.data("checking", true) is called.
When the ajax event has been finished, input.data("checking", false) is called.
Now I want to make a custom form submit that waits for all input in this form to be on input.data("checking") === true.
My code so far, without the question applied:
$(document).on("submit", "form", function(event) {
event.target.checkValidity();
event.preventDefault();
event.stopPropagation();
//TODO: prevent this when not everything is checked
var dataSerialized = $(this).serialize();
var service = $(this).attr("action");
$.ajax({
url: "services/" + service + ".php",
data: dataSerialized,
type: "POST",
cache: false,
success: function(html) {
if (html == "1") {
//TODO: load page from json callback
//loadPage(onsuccess);
}
else {
loadPage("error");
}
},
error: function(html, message) {
finalError(message);
}
});
});
How could I make this function wait (non-blocking!) until all ajax events are finished?
Suppose to create a function checkDone which returns true when input.data("checking") == false for all input in the form, you could do:
$(document).on("submit", "form", function(event) {
event.target.checkValidity();
event.preventDefault();
event.stopPropagation();
var that = $(this);
var interval = setInterval(function() {
if(checkDone(that)) {
clearInterval(interval);
var dataSerialized = that.serialize();
var service = that.attr("action");
$.ajax({
url: "services/" + service + ".php",
data: dataSerialized,
type: "POST",
cache: false,
success: function(html) {
if (html == "1") {
//TODO: load page from json callback
//loadPage(onsuccess);
}
else {
loadPage("error");
}
},
error: function(html, message) {
finalError(message);
}
});
}
}, 500);
});
In this way you check every 0.5 seconds if you can submit the form after all inputs are validated, and if so the interval is cleared and the form submitted.
However I would recommend not to remove standard server side validation on post submit.

stop/cancel form jquery form action from javascript?

I have a form that is submitted via jquery for an instant image upload. When the image starts to upload via the form, i show a cancel upload button via jquery. Now is there a way using jquery, i can stop/cancel the form submission on the click property of the cancel upload button? What i do currently is that i delete the current upload from the databse using ajax and then refresh the page. this will not upload the image but i am trying to find something that will not let the page refresh.
$('.deleteimage').live("click", function () {
var ID = $(this).attr("id");
var IPString = $(".ipvaluetable").val();
var dataString = 'msg_id=' + IPString;
document.getElementById("preview").style.visibility = "hidden";
$(".preview").slideUp('slow', function () {
$(this).remove();
});
document.getElementById("deleteimage").style.visibility = "hidden";
$.ajax({
type: "POST",
url: "http://schoolspam.com/delete_image.php",
data: dataString,
cache: false,
success: function (html) {}
});
location.reload();
return false;
});
Well on cancel you can do event.preventDefault(); and then return false.
Example
$('.cancel').on('click', function(e){
e.preventDefault();
return false;
});
Please use below code and also see my comments :
$('.deleteimage').live("click", function (e) {
e.preventDefault();//Stops default behaviour
var ID = $(this).attr("id");
var IPString = $(".ipvaluetable").val();
var dataString = 'msg_id=' + IPString;
document.getElementById("preview").style.visibility = "hidden";
$(".preview").slideUp('slow', function () {
$(this).remove();
});
document.getElementById("deleteimage").style.visibility = "hidden";
$.ajax({
type: "POST",
url: "http://schoolspam.com/delete_image.php",
data: dataString,
cache: false,
success: function (html) {}
});
//location.reload();//This one needs to be removed so as to stop the reload
return false;
});

Categories

Resources