how restart Jquery function if not complete - javascript

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);

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.

Prevent multiple click events and change target value

I have UI with a list of users in a table. Each entry / user has two buttons. One of the buttons is a 'check' button.
<button type="submit" id="$id_from_db" class="bg-aqua btnCheckUser">Check</button>
When a check button is clicked for a particular user a POST request is sent to a server. While the request is loading all buttons should be disabled, the button which started the request should change its class from bg-puple to bg-aqua
and its text from Check to Checking.... If the request returns an error (which is indicated by result having the value 1) the button should change its class from bg-aqua to bg-danger. If there is no error the class should change from bg-aqua to bg-navy and the text from Checking... to User Okay.
I'm able to achieve this but it does not only affect the button which started the request but all buttons.
This is my code:
$(document).on("click", ".btnCheckUser", function() {
var Item_Number = $(this).attr("Item_Number");
/************************** MANIPULATE BUTTONS *******************************************************************************/
$(this).removeClass('bg-purple').addClass('bg-aqua');
$(this).html('Checking ...');
$(this).attr("disabled", true);
$('.btnViewUser').attr("disabled", true);
/******************************* PROCESS AJAX **************************************************************************/
var value = {
Item_Number: Item_Number
};
$.ajax({
url: "./plugins/serverside/CheckUserStatus",
type: "POST",
data: value,
success: function(data, textStatus, jqXHR) {
var data = jQuery.parseJSON(data);
if (data.result == 1) {
$(this).removeClass('bg-aqua').addClass('bg-danger');
$("#CheckUser").html('Failed!');
$('.btnCheckUser').attr("disabled", false);
$('.btnViewUser').attr("disabled", false);
setTimeout(function() {
var table = $('#User_Table').DataTable();
table.ajax.reload(null, false);
}, 3500);
} else if (data.result == 2) {
//------------------------ IF User Okay -------------------------------------------------------------------------------------------------------------------
$("#CheckUser").removeClass('bg-aqua').addClass('bg-navy');
$("#CheckUser").html('User Okay');
$('.btnCheckUser').attr("disabled", false);
$('.btnViewUser').attr("disabled", false);
}
How can I fix this and only affect the button which started the request, but still disable all buttons when a request is loading?
JSFiddle
I stripped the code down to the parts which matter for the button logic. I'm using a dummy API and I randomly generate the result value as I have no access to the actual API you're using.
$(() => $('.btnCheckUser').on('click', ({ target }) => clickHandler(target)));
function clickHandler(button) {
// Disable all buttons when one of them is clicked
$('.btnCheckUser').prop('disabled', true);
$('.btnViewUser').prop('disabled', true);
// Remove all non standard classes, then add 'loading' class and text
$(button).removeClass('bg-purple').removeClass('bg-navy').removeClass('bg-danger').addClass('bg-aqua');
$(button).text('Loading...')
$.ajax({
url: 'https://reqres.in/api/users?delay=3',
success: raw => {
// Random result value
const result = Math.random() > 0.5 ? 1 : 2;
if (result === 1) {
// Something went wrong, add 'danger' class and text
$(button).addClass('bg-danger');
$(button).text('Failed!')
} else if (result === 2) {
// Everything went fine, add 'success' class and text
$(button).addClass('bg-navy');
$(button).text('Success!');
}
},
error: () => {
// Add 'danger' class if something goes wrong
$(button).addClass('btn-danger');
},
complete: () => {
// Enable all buttons as we got a response
$('.btnCheckUser').prop('disabled', false);
$('.btnViewUser').prop('disabled', false);
// Remove 'loading' class as we got a response
$(button).removeClass('bg-aqua');
}
});
}
This should give you the expected behavior.
hello there this is truly easy what you have to do is
function TheClickerFunction(){
$("body").on("click",".YourButton",function(){
//this will only affect the clicked element
$(this).attr("disabled",true);
});
}
$(document).ready(function(){
TheClickerFunction();
});
/*
i think creating a global counter and increment it on each element would b better*/
var GlobalCounter= 0;
function DynamicBuilder(){
var stringBuilder="";
for(var i = 0; i< lengthOfYourElement ; i++){
GlobalCounter+=1;
stringBuilder+="<input type='submit' id='myButton"+GlobalCounter+"'></input>";
}
$("body").append(stringBuidler);
}
in this way each time a click is made
$(".yourClass").click(function(){
var elementID = $(this).attr("id");
//here you can do what ever you want with its id
})
*/

Repeated Ajax calls using SetTimeout javascript, unexpected execution

I list of users in a html table that is dynamically created on page load. Each row has an inline button and each button has onclick="functionName(userId)", calls the following functions:On click show the bootstrap model pop up and then after starts calling ajax. The problem is stopping the ajax calls after user has closed model,and if user clicks on another row/user pass the current userId. for some reason, sometimes ajax calls stop and sometimes dont. Previous userId is also being saved somewhere which is resulting double or triple calls in a given interval. Thank you for your insights.
//This function gets called from each row passing its userId:
var timer = null;
function RTLS(id) {
$('#RTLSModal').modal('show');
window.clearTimeout(timer);
$('#RTLSModal').on('hidden.bs.modal',
function() {
window.clearTimeout(timer);
timer = 0;
$('#RTLSModal .modal-body').html("");
$('#RTLSModal').data('bs.modal', null);
});
$('#RTLSModal').on('shown.bs.modal',
function () {
GetRealTimeScans(id);
});
}
function GetRealTimeScans(id) {
var html = '';
$.ajax({
url: '/api/v1/computers/GetRealTimeKeys?computerId=' + id,
typr: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (scans) {
if (scans.length > 0) {
$.each(scans,
function (index, value) {
//create html
});
$('#RTLSModal .modal-body').html(html);
} else {
html += '<div class=""><h3 style="text-align: center;">No one around</h3></div>';
$('#RTLSModal .modal-body').html(html);
}
},
complete: function () {
timer = setTimeout('GetRealTimeScans('+id+')', 10000);
}
});
}
So abort the Ajax call so it stops
var timer = null;
var ajaxCall;
function cleanUp () {
if (timer) window.clearTimeout(timer);
if (ajaxCall) ajaxCall.abort()
}
and when you make the call
cleanUp()
ajaxCall = $.ajax({})
.done( function () {
ajaxCall = null
timer = window.setTimeout(function(){}, 10000)
});
And when you bind the events to the modal, you need to remove the previous event handler.
$('#RTLSModal')
.off('hidden.bs.modal shown.bs.modal')
.on('hidden.bs.modal', function() {})
.on('shown.bs.modal', function() {});

AJAX sending multiple requests after button click

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){
}
});
});

Why does this JavaScript freeze IE6?

When you click, "Add to Bag" on this page, it freezes IE6 every time. How can I figure out why it is freezing? Does anyone have a more direct answer?
totallytrollbeads {dot} com {slash} Safety0.html
function update() {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/cgi-bin/ajax_cart_count.cgi',
timeout: 2000,
success: function (data) {
// If bag is empty, it's see through.
if (data.cart_count == 0) {
$(".shopping_bag").css("opacity", ".2");
}
// If bag is not empty, it's not see through.
else {
$(".shopping_bag").css("opacity", "1");
}
$("#bag_total").html(data.grand_total);
$("#bag_count").html(data.cart_count);
window.setTimeout(update, 15000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#bag_total").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
})
}
$(document).ready(update);
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// $(".add_to_cart_form").click(function () {
// $('.bypass_add_to_cart_form').ajaxForm({ success: myBox });
// });
function loading() {
$("#loadingContent").show();
}
function myBox(resptext, statustext) {
$("#loadingContent").hide();
Boxy.ask(resptext, ["View Bag", "Continue Shopping"], function (val) {
if (val == "View Bag") {
document.location.href = "/cgi-bin/store.cgi?action=view_cart";
}
if (val == "Continue Shopping" && product_detail == 1) {
history.go(-1);
}
}, {
title: "Add to Bag"
});
$('.bypass_add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
update();
return false;
}
/*
This tells the ajax-style add to cart that
it's on a product detail page so if the
user clicks "Continue Shopping" it takes
them back on step in their history.
*/
$('.search_view').click(function () {
product_detail = 0;
});
$('.product_view').click(function () {
product_detail = 1;
});
It's not easy to debug a thing that freezes immediately from the outside. But it's always a good idea to cleanup the whole, remove things that are not essential, check the functionality and then do the next step.
For example this:
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
It's not hard to see that have this part twice there.
Put a little more accuracy into your application instead of copy&paste.

Categories

Resources