Execute jquery functions in order - javascript

function fn_one() {
$('#search-city-form').trigger('click');
}
function fn_two() {
$("form input[name='tariffId']").val("137");
$('#search-city-form').trigger('click');
}
function fn_three() {
$("form input[name='tariffId']").val("138");
$('#search-city-form').trigger('click');
}
function fn_four() {
$("form input[name='tariffId']").val("139");
$('#search-city-form').trigger('click');
}
$(document).on('click','.ui-menu li',function(){
fn_one();
fn_two();
fn_three();
fn_four();
});
I have this js code. I need to execute the functions in on(click) in order, i.e. fn_one() goes first, fn_two() second and etc.
Please give simple example of how can I achieve this.
Edit: OK, I used the next function to be executed in the previous one but still I was getting erraneous data. So I think I realized why this is happening. I will explain what $('#search-city-form').trigger('click'); does. It triggers a form submit which makes an Ajax call and other function are not waiting till ajax request is complete. So how do I make it to wait for ajax request to complete?
EDIT 2:
Event handler for $('#search-city-form'):
$('#cdek').submit(function() {
var formData = form2js('cdek', '.', true, function(node) {
if(node.id && node.id.match(/callbackTest/)) {
return {
name : node.id,
value : node.innerHTML
};
}
});
var formDataJson = JSON.stringify(formData);
// console.log(JSON.stringify(formData));
document.getElementById('testArea').innerHTML = 'Отправляемые данные: <br />' + JSON.stringify(formData, null, '\t');
$.ajax({
url : 'http://api.cdek.ru/calculator/calculate_price_by_jsonp.php',
jsonp : 'callback',
data : {
"json" : formDataJson
},
type : 'GET',
dataType : "jsonp",
success : function(data) {
console.log(data.result.price);
} else {
for(var key in data["error"]) {
console.log(data["error"][key]);
}
}
}
});
return false;
});

I'll do this. If you need validate when the function has triggered, maybe you need to work with promises.
function fn_one() {
$('#search-city-form').trigger('click');
fn_two()
}
function fn_two() {
$("form input[name='tariffId']").val("137");
$('#search-city-form').trigger('click');
fn_three()
}
function fn_three() {
$("form input[name='tariffId']").val("138");
$('#search-city-form').trigger('click');
fn_four()
}
function fn_four() {
$("form input[name='tariffId']").val("139");
$('#search-city-form').trigger('click');
}
$(document).on('click','.ui-menu li',function(){
fn_one();
});

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.

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

How to stop running timeout jquery function on click and run new function?

I'm trying to update a view with ajax call in every 5 seconds. I've done it in the following way.
function getData(a, b, c) {
$.ajax({
url : 'url',
success : function(data) {
$("#result").html(data);
setTimeout(getData, 5000, a, b, c);
}
})
}
$(document).ready(function() {
getData(1, 2, 3);
});
$('.btn').click(function(){
getData(4,5,6);
});
But, in this way as many functions are running as many click.
I need to stop the previous one and run new one or change the parameter of running function.
Use Ajax abort() function to stop the request when button is clicked and start a new one...
Here i have an example for you, that how abort works... take a look at code and try this...
<script>
var prev_request = false;
var xhr;
var myTimeoutReq;
//var myCondition = true,
function getData(a, b,c,myCondition )
{
if(prev_request == true)
{
xhr.abort();
}
xhr = $.ajax({
url : 'url',
beforeSend: function( xhr ) {
prev_request = true;
},
success : function(data) {
$("#result").html(data);
if(myCondition == true)
{
myTimeoutReq = setTimeout(getData, 5000, a, b, c,true);
}
else
{
clearTimeout(myTimeoutReq);
}
},
complete: function( xhr ) {
prev_request = false;
}
});
}
$(document).ready(function() {
getData(1, 2, 3, true);
});
$('.btn').click(function(){
getData(4,5,6,false);
});
</script>
You need to use clearTimeout to finish previous timeout for that you need to assign the setTimeout returned object first. Declare a global object to assign timeout object to that it could be assessed through other functions.
Assigning the timeout object
someGlobalTimeoutObject = setTimeout(getData, 5000, a, b, c);
Clearing timeout object
clearTimeout(someGlobalTimeoutObject);
function getData(a, b, c) {
if(detData.ajax) {
detData.ajax.abort();
clearTimeout(getData);
}
detData.ajax = $.ajax({
url : 'url',
success : function(data) {
$("#result").html(data);
setTimeout(getData, 5000, a, b, c);
}
});
}

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

Run the function after the effects is done

How can I run the function after the effect is done like delaying running the specified function after a certain time? I tried set timeout and it didn't work for me.
Here my Code
<script>
$("#findtext").keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13)
{
explodeEffect();
}
$.ajax({
url: 'resultFindFriend.php',
type: 'post',
async: false,
data: { dataFriend: $(this).val() },
success: function (data) {
$('.outputfindfriend').html(data);
}
},setTimeout(150));
});
function explodeEffect() {
$("#explodesearchresult").toggle("explode");
setTimeout(1000);
window.location("http://localhost/index.html");
};
$("#buttonfriend").click(function () {
explodeEffect();
return false;
});
</script>
This is doable with jQuery's .toggle(), just add a function as the second argument.
Try this:
function explodeEffect() {
$("#explodesearchresult").toggle(400, function() {
setTimeout(function() {
window.location.href = "http://localhost/index.html";
}, 1000);
});
}
This will redirect the page 1 second after the explode effect has finished.

Categories

Resources