double calls ajax using jquery - javascript

two calls:
$('#add').live('click', function() {
$('.simplebox').slideUp(200, function() {
$('html, body').animate({scrollTop:140}, 350, function() {
$('#loading-add').slideDown(300, function() {
$.ajax({
type: "POST",
url: "..",
data: getDataToPost(),
cache: false,
success: function(data){
alert(data);
$('#loading-add').delay(1000).fadeOut(200, function() {
$('#successfull-add').fadeIn(200);
});
}
});
});
});
});
})
But if i call to the ajax immediately after the live event, it calls on time (as it should be):
$('#add').live('click', function() {
$.ajax({
type: "POST",
url: "..",
data: getDataToPost(),
cache: false,
success: function(data){
alert(data);
$('#loading-add').delay(1000).fadeOut(200, function() {
$('#successfull-add').fadeIn(200);
});
}
});
})
There are any ideas why it happens? really strange..
Thank you.

Try using queue():
$('.simplebox').slideUp(200);
$('.simplebox').queue(function() {
$('body').animate({scrollTop:140}, 350);
$('body').queue(function() {
$('#loading-add').slideDown(300);
$('#loading-add').queue(function() {
//ajax call
});
});
})

Related

How do I redirect to another page in JS / jQuery after sending a form?

I'm trying to make a JS script that works on the same form page. Everything works up until redirecting after a successful login.
$(document).ready(function() {
$('#loginForm').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'goLogin.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'html'
}).done(function(data) {
$('#results').fadeOut('slow', function() {
$('#results').fadeIn('slow').html(data);
window.setTimeout(function() {
window.location.href = 'index.php';
}, 5000);
});
}).fail(function() {
alert('Error!');
});
});
});
$.ajax({
url: 'goLogin.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'html',
success: function(data){
$('#results').fadeOut('slow', function() {
$('#results').fadeIn('slow').html(data);
window.setTimeout(function() {
window.location.href = 'index.php';
}, 5000);
});
},
error: function(data){
alert('Error!');
}
});
Please check this code...Replace your ajax section...

when click on the element, ajax request loaded data in first time, after first time prevent ajax request

$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
Use a flag, check for it and set it to false on complete
let shouldAjax = true;
// later
if (shouldAjax) {
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) { //stuffs
},
complete: function() {
$(this).data('requestRunning', false);
shouldAjax = false;
}
});
}

Create function inside deprecated javascript function

Currently I have a javascript file structure which seems deprecated to me, inside this function there's an ajax call, and after the ajax call giving response I want to add ajax function, but if I have to define it 1 by 1 for every ajax response type, it will consume a lot of space so I need to make a function which will call this ajax function, but I don't know where to place this function that I will make. here's my code
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onPending: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onError: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onClose: function() {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
}
});
}
});
});
}
});
I just added a successcallback and an errorcallback to the POST function. But if you want you can ignore those functions and implement the success and error functionality inside the function itself without using callbacks.
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
//Define a function to send the POST request here.
//////////////////////////////////////////////////
var sendPayment = function(param, successcallback, errorcallback) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: param.id,
message: param.message
}
success: function(data) {
successcallback(data);
},
error: function(error) {
errorcallback(error);
}
});
};
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
//Call sendPayment method and you can
//pass whatever you want.
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onPending: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onError: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onClose: function() {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
}
});
}
});
});
}
});

Load reveal modal while an ajax is running

Hi I am calling an ajax from my php page and while the ajax is running i would like to load a image on foundation reveal modal.
this in my code.
<div id="loadinimg" class="reveal-modal" data-reveal>
Loading!!!!!!!!!!!!!!!
</div>
$('.print-button').click(function() {
$.when(
$.ajax({
url: 'newphp1.php',
type: "POST",
beforeSend: function() {
$('#loadinimg').foundation('reveal', 'open');
},
data: {
selected_date: '<?php echo $GLOBALS["selected_date"] ?>'
},
error: function(data){
},
success: function(response){
alert(response);
console.log(response);
},
complete: function() {
$('#loadinimg').foundation('reveal', 'close');
}
})).done(
$.ajax({
url: 'newph2p.php',
type: "POST",
data: {
selected_date: '<?php echo $GLOBALS["selected_date"] ?>'
},
error: function(data){
},
success: function(response){
console.log(response);
console.log(response);
location.reload();
}
}));
});
but the reveal modal is getting popped up only at the end of the ajax execution. what can be the problem?
You can use beforeSend and complete option of ajax like one below:
$.ajax({
url: 'newphp.php',
type: "POST",
async: false,
beforeSend: function() {
$('#loadinimg').foundation('reveal', 'open');
},
error: function(data){
},
success: function(response){
alert(response);
console.log(response);
},
complete: function() {
//close the loading image
}
}
UPDATE
$.when(
$.ajax({
url: 'newphp.php',
type: "POST",
beforeSend: function() {
$('#loadinimg').foundation('reveal', 'open');
},
error: function(data){
},
success: function(response){
alert(response);
console.log(response);
},
complete: function() {
//close the loading image
}
})).done(function(){
//make another ajax call here
});
UPDATE 2
This might be the only way left now!! Just set a global variable in js file like one below:
var ajax1Complete=false;
$.when(
$.ajax({
url: 'newphp.php',
type: "POST",
beforeSend: function() {
$('#loadinimg').foundation('reveal', 'open');
},
error: function(data){
},
success: function(response){
alert(response);
console.log(response);
ajax1Complete=true;//set it on success
},
complete: function() {
//close the loading image
}
})).done(function(){
if(ajax1Complete)
{
//make another ajax call here and onsuccess set ajax1Complete to false
}
});

making ajax call fire only once

I have an ajax call that is being fired multiple times.
I have used e.stopImmediatePropagation() and return false to prevent it from firing more than once. Is there another sure shot way to prevent ajax call more than once.
$(document).on('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
e.stopImmediatePropagation();
return false;
});
You can use jQuery .one()
$(document).one('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
});
var n = null;
$(document).one('click', '#button1', function(e){
$.ajax({
url: 'https://gist.githubusercontent.com/anonymous/9a6997f09de9b68c59b2/raw/f7d7b756005ad6d2b88cf0211f78a2990d7d2dc7/content.json',
data: {},
method: 'HEAD',
success: function(data, textStatus, jqxhr) {
console.log(jqxhr.getAllResponseHeaders())
$("body").append("<br>textStatus: " + textStatus + "<br>count: " + ++n)
},
error: function(err){
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1">click</button>
You can use jquery.data() to store a boolean to indicate whether your function has been run before.
$(document).on('click', '#button1', function(e) {
$button = $("#button1");
if ($button.data("pressed") !== true) {
$.ajax({
url: 'http://non-existentpage',
data: {},
method: 'POST',
success: function(data) {
alert('ajax');
$button.data("pressed", true);
},
error: function(err) {
alert('ajax');
$button.data("pressed", true);
}
});
}
});
#button1 {
border: 1px solid #000;
display: inline;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button1">ajax</div>
You could also add a condition checking if the button has already been clicked by setting a variable to true after it has been clicked:
window.document_clicked = false;
$(document).on('click', '#button1', function(e){
if(!window.document_clicked){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
window.document_clicked = true;
},
error: function(err){
}
});
}
});
Adding async: false to your current function
or USE .click
$('#button1').click(function(e){
});
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
$(document).on('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
async: false,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
e.stopImmediatePropagation();
return false;
});
Try this instead
$('#button1').click(function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
Much simpler and it should fix that issue of multiple ajax calls.
You also shouldn't have to return false.

Categories

Resources