Hold ajax call in every minute calling section - javascript

i am calling ajax every second in page..
Here the server page returns randomly generated number,using this number(converted into seconds) i am triggering another function in ajax success .it works
My problem
suppose random number = 5 means trigger() function called after 5 seconds using setTimeout,but rember ajax call is triggering every 1 second so trigger function also called many time.
i want to make ajax call wait untill trigger function execution.Which means i wanna pause that ajax call untill 5 seconds after that resume
How can i do this ?
My coding
//this ajax is called every minute
$.ajax({
type: "POST",
url: 'serverpage',
data: ({pid:1}),
success: function(msg) {
var array = msg.split('/');
if(array[0]==1){
setTimeout(function() { trigger(msg); },array[1]+'000');
}
}
});
//and my trigger function
function trigger(value)
{
alert("i am triggered !");
}
server response maybe
1/2 or 1/5 or 1/ 10 or 1/1
here 1/3(this is converted into seconds)

It looks like you should fire the ajax call in your trigger function, or on the error callback. Fire it once at page ready, and then fire it when your success function is called.
function ajaxCall() {
$.ajax({
type: "POST",
url: 'serverpage',
data: ({pid:1}),
success: function(msg) {
var array = msg.split('/');
if(array[0]==1){
setTimeout(function() {
trigger(msg);
ajaxCall();
}, parseInt(array[1])*1000);
}
},
error: function() {
setTimeout(ajaxCall, 1000);
}
});
}
$(ajaxCall);
Note: you should reply with some json instead of your custom data format "1/3". Something like "{success:1,delay:3}" would be much more reliable.

you can call your ajax function recursively from your 'success' callback function or in your case better would be from trigger function.

Rather than having your AJAX call in a timer, just recall it after each execution of the trigger function.
//and my trigger function
function trigger(value)
{
alert("i am triggered !");
MyAjaxFunction();
}
You have to call it once too at page load:
$(document).ready(function(){
MyAjaxFunction();
});

Related

Run ajax request after specific time

Hello I'm working on a website with a color slider that append a specific color page to the DOM after a slide change. I want people to still be able to go through the different slide pretty quickly and load the ajax page only if the user didn't change the slide for a specific time (for example 1000ms).
I tried setInterval, setTimeout and the ajax timeout parameter but it isn't working, it just adds requests to the call stack and after the timeout duration it appends the div 5 times.
Here's the ajax call:
$.ajax({
url: "/wp-admin/admin-ajax.php",
type:"POST",
data: {
action: "my_custom_color",
post_link: post_ID
}, success: function (response) {
$('.color').prepend(response);
},
})
I want to be able to do something like this:
colorsMonoSlider.events.on('indexChanged', () => {
setTimeout(() => {
customizedFunction()
}, 1000);
});
But without filling the call stack (maybe emptying it at each call), the ajax request should only trigger once after the timeout, I can't disable the slider navigation or use async: false because as I said users need to be able to spam click to go through the slider fast.
Any tips welcome, thanks in advance.
You need to cancel both your ajax call and timer functions before invoking again.
Assuming the customized function has the ajax call.
var xhr,timer;
function customizedFunction(){
xhr && xhr.abort();
xhr = $.ajax({
url: "/wp-admin/admin-ajax.php",
type:"POST",
data: {
action: "my_custom_color",
post_link: post_ID
}, success: function (response) {
$('.color').prepend(response);
},
})
}
colorsMonoSlider.events.on('indexChanged', () => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
customizedFunction()
}, 1000);
});

Timer in Ajax - Preemption [duplicate]

This question already has an answer here:
Ajax too slow - Recursion
(1 answer)
Closed 4 years ago.
So this thing was going in my mind for a long time whether the timer that is given in an AJAx after which it has to send another request, what if it is smaller than the actual time taken by the requested file to complete its operation.
for example, consider the below code,
<div class="item"></div>
<script>
function timeLeft() {
$(".item").each(function() {
$this = $(this);
var dataString = {s: "//some data", st: "<?echo $stamp?>"};
$.ajaxSetup({cache:false});
$.ajax({
type: "POST",
url: "get_content_home.php",
dataType: "html",
data: dataString,
success: function(result) {
$this.html(result);
}
});
});
}
window.setInterval(function() {
timeLeft();
}, 100);
</script>
the timer given here is 100ms and the file get_content_home.php will be requested every 100m. What if get_content_home.php takes 500ms to complete its operations. Will the get_content_home.php be preempted and will be requested again? or will the timer wait and delay itself.
Thanks in advance.
It's worse than you thought since the ajax request is in a loop.
What's gonna happen is actually :
window.setInterval call timeLeft
timeLeft call the AJAX request to get_content_home.phpone time for each .item element.
Let's say one AJAX call take 500ms, you'll do this five time before the first AJAX request return something (hence 5xnumber of .item calls before one result).
To stop this craziness, put your AJAX call outside of the loop and put the window.setInterval in the AJAX callback function:
$.ajax({
type: "POST",
url: "get_content_home.php",
dataType: "html",
data: dataString,
success: function(result) {
$this.html(result);
window.setTimeOut(function() {
timeLeft();
}, 100);
}
});
and call timeLeft(); just once at the start.

Independent jquery functions execute consecutively when one is called

My problems seems basic, yet I have tried a lot of different ways of putting these functions on one html file to no avail. The problem is that, when the 1st function is called, the second also runs, leaving me with the results of the second function all the time. I have no idea what I am doing wrong, please help. Here is the code in question.
<script>
$(document).ready(function () { // Make sure the elements are loaded on the page
// Listen for a click event on the button
$('#buttonON').click(funct);
$('#buttonOFF').click(funct2);
});
// Now define the function
function favfunct(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "1", "caroff" : "0"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
function funct2(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "0", "caroff" : "1"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
}
</script>
You have omitted the closing brace from the function favfunct().
Please use this,
<script>
$(document).ready(function () {
function funOne(){
};
function funTwo(){
};
$('#buttonON').live('click',function(){
funOne();
});
$('#buttonOFF').live('click',function(){
funTwo();
});
});
NOte: initialize function before use and initialize them into document ready.

Ajax recursive function work strange

Hello guys here's my code:
var ajax={
chiamata:function(target,url,opzioni){
if (!tools.array_key_exists('caricamento',opzioni)){
opzioni['caricamento']=1;
}
var dati=url.split('?');
$.ajax({
type: opzioni['type'],
url: url,
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
data: dati[1],
dataType: "html",
success: function(msg){
if (opzioni['caricamento']!=0){
ajax.printLoading();
}
$(target).html(msg);
},
error: function(){
alert("Chiamata fallita!");
}
})
},
printLoading:function(){
var body="#colonnaDX";
$(body).ajaxStart(function(){
$(body).append('<div id="loading"><img src="graphic/IMAGE/spinner.gif"/>Loading...</div>');
})
.ajaxStop(function(){
$('#loading').remove();
});
}
},
//Recursive function
var object={
checkAzione:function(target,url,opzioni,interval){
if (!interval)
interval=60000;
ajax.chiamata(target,url,opzioni);
setTimeout(function() {
this.checkAzione(target,url,opzioni,interval);
}, interval);
}
}
$(document).ready(function(){
object.checkAzione(
'#colonnaDX',
'someactions.php',{
'caricamento':0
},
10000
);
})
I'll try to explain the problem as better as i can, When the document is ready, the function "checkAzione" starts and it makes some stuff like DB calls etc, this kinds of ajax calls don't need any visual loading like spinner etc so in the array "opzioni" i set a flag 'caricamento':0 (same of 'loading':0) just check my ajax object to see what i mean, it works until i make some ajax calls that using 'caricamento':1, from that moment every ajax calls in my recursive function makes the "printLoading"... Any tips????
ajaxStart and ajaxStop are global, you add them to the body. You probably shouldn't use ajaxStart/Stop in this case, just add the functionality to your ajax listeners (success and error).

Jquery Wait Until AJAX Call is Done

I have an ajax function for saving a forms data. I want it to remain asynchronous because the users can hit save any time. However, I have another function that converts the form to a PDF and I want it to run the save function before creating the PDF (in case the users have added more data). Is there a way to make $('input.submit') wait for save to finish before opening the pdf? Below is the jQuery I am using:
$("button#save").on('click', function (){
$.ajax({
type: 'POST',
url: '<?php echo matry::base_to('utilities/crm/field_day_save');?>',
data: $("form#trip_form").serialize(),
dataType: 'json',
success: function (data)
{
$("#alerts").html(data.alert);
$("#form_id").val(data.id);
}
});
});
$("input.submit").on('click', function(event){
event.preventDefault();
$("button#save").trigger('click');
window.open('<?php echo matry::base_to('custom_worddocs/field_day');?>' + '&fd_id=' + $("#form_id").val());
});
In short, I want $('button#save').click() to remain asynchronous, but I want $(input.submit) to wait for button save to complete before opening new window.
jQuery's ajax function returns a jqXHR object which, among other things, behaves like a deferred.
By only calling window.open from within the then function, it'll wait for the AJAX to complete:
$("button#save").on('click', function () {
var jqXHR = $.ajax({ /* your config... */ });
$("input.submit").one('click', function(event) {
event.preventDefault();
$("button#save").trigger('click');
jqXHR.then(function () {
window.open('<?php echo matry::base_to('custom_worddocs/field_day');?>' + '&fd_id=' + $("#form_id").val());
});
});
}
Have your click handler return a promise object, then use triggerHandler() to trigger the click event and get it's return value.
$("button#save").on('click', function (){
return $.ajax({
...
and
...
$("button#save").triggerHandler('click').done(function(){
window.open(...);
});
...
Proof of concept: http://jsfiddle.net/SRzcy/

Categories