jQuery recursive ajax poll using setTimeout to control the poll interval - ajax

$(document).ready(function() {
(function poll() {
setTimeout(function() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 5000
}), 5000
});
})();
});​
This just keeps executing as fast as the server can respond but I was hoping it would only poll every 5 seconds. Any suggestions?
EDIT: I should add, 5 seconds after the request has completed would be preferable.

It seems that you've managed to get your setTimeout delay argument written in the wrong place.
$(document).ready(function() {
(function poll() {
setTimeout(function() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 5000
}) //, 5000 <-- oops.
}, 5000); // <-- should be here instead
})();
});​
If you follow the braces, you'll see that you're calling setTimeout like:
setTimeout(function () {
$.ajax(), 5000
})
and should be
setTimeout(function () {
$.ajax();
}, 5000)
This should call the AJAX poll 5 seconds after the previous one has completed.

If it should poll every 5 seconds and not necessarily 5 seconds after completing the last request, you could use setInterval. Don't know if that's acceptable, but it would make recursion unnecessary.
function poll() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json"
});
}
setInterval(poll, 5000);

Incase you wanted to use jQuery's promise syntax, rather than callback syntax here's another tidy way.
function poll() {
$.get('http://your-api-endpoint.com')
.done(function() {
// 200 - OK response
})
.fail(function() {
// Error Response
})
.always(function () {
setTimeout(function() {
poll();
}, 5000);
});
}
poll();

Related

I have 2 functions in my Javascript.One has multiple ajax calls to get the data and other displays the data.The functions are not executed in sequence [duplicate]

This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
How to wait until jQuery ajax request finishes in a loop?
(5 answers)
Closed 5 years ago.
Sample Code
$( document ).ready(function() {
getData();
LoadData();
});
function getData() {
alert('getData');
Data='';
$.ajax({
type: "GET",
url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {},
processdata: true,
async: false,
success: function (json) {
Data= json;
alert('Data:' + Data);
},
error: function (e) {
alert('error ' + e.status + ' ' + e.responseText);
}
});
}
function LoadData() {
alert('LoadData');
}
The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData
The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}
What am I doing wrong.Please help me!!
why don't you call LoadData() after success?
like below
$( document ).ready(function() {
getData();
});
function getData() {
alert('getData');
Data='';
$.ajax({
type: "GET",
url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {},
processdata: true,
async: false,
success: function (json) {
data= json;
alert('Data:' + data);
LoadData();
},
error: function (e) {
alert('error ' + e.status + ' ' + e.responseText);
}
});
}
function LoadData() {
alert('LoadData');
}
UPDATE :
as you said , you are having multiple ajax calls,
one work around could be ,
try setting flag for each ajax call and make them true on respective success event , and lastly you need to call loadData() from all success completion and in loadData(){ ...} body check all the success are completed or not,
$( document ).ready(function() {
getData();
$flag1= flase;
$flag2= flase;
$flag3= flase;
$flag4= flase;
});
function LoadData() {
if($flag1 && $flag2 && $flag3 && $flag4)
{
alert('LoadData');
}
}
and in each ajax call's success
success: function (json) {
data= json;
alert('Data:' + data);
$flag1=true;
LoadData();
},
and don't forget to make all flag false in $(document).ready(){}
Inside success function call the LoadData() function
success: function (json) {
Data= json;
alert('Data:' + stackMonthData);
LoadData();
},
AJAX is asynchronous process ans ajax request start in different thread, so JavaScript not wait for AJAX response, so there is two possible way to handle it
Make AJAX request in synchronous process, by pass async:false in jquery AJAX parameter
call getData() function in AJAX callback liks success/error or done/faild callback something like
$.ajax({
// your code
}).done(function(data) {
getData()
}).fail(function(data){
});

jQuery.ajax request progress bar

Okay, this is the same post as my last post which got downvoted and marked as duplicate. Here's the post again but now with the explaination why the questions from What is the cleanest way to get the progress of JQuery ajax request? didn't work.
I have an AJAX request in where I insert stuff in the database and send 2
emails. I'd like to show the progress of the AJAX request.
Currently I tried:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('title').html((100 * e.loaded / e.total) + '%');
}
});
return xhr;
},
complete: function() { /*here some stuff*/ }
});
However, it doesn't change the title during the request, but after the request it sets it to 100%. Is there any way I can get what I want? So that when 50% in the AJAX file is executed it shows 50% and does the progress like that.
The next thing I tried is:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with download progress
}
}, false);
return xhr;
},
complete: function (result){}});
However then I only get a 1 in the title, and immediately when I click my button and the AJAX gets called.
Last, I tried the second answer:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
complete: function (result) {}
}).progress(function(e, part) {
console.log(part);
}).progressUpload(function()
{
});
However this gives:
jq-ajax-progress.min.js:1 Uncaught TypeError: Cannot read property 'upload' of undefined
at Function.e.ajax (jq-ajax-progress.min.js:1)
at a.validator.submitOrderForm (checkout.js:108)
at d (jquery.validate.min.js:4)
at HTMLFormElement.<anonymous> (jquery.validate.min.js:4)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.r.handle (jquery.min.js:3)
I tried a lot of things already but none seem to work.

Refreshing a AJAX call

I have an AJAX call in cordova application.I have checked the availability of internet connection before actual call. But some times in mobile internet connectivity is lost for few seconds after the call is made and thus device does not read any reply from web-service. It goes to error part of Ajax call. I wants to make this Ajax call again so that DOM should get created
call AJAX function is
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if(isOnline == false)
{
alert('Internet is not running. Please reconnect and try');
return 0;
}
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
// alert(JSON.stringify(response));
errorFunction(response);
}
});
}
If you want to retry after an error, you can just re-call your function recursively, or do something like this to prevent too many retries:
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if (isOnline == false) {
alert('Internet is not running. Please reconnect and try');
return 0;
}
function tryAjax(retryCount) {
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
if (retryCount > 10) {
errorFunction(response);
} else {
tryAjax(retryCount + 1);
}
}
});
}
tryAjax(0);
}

How do I fadeIn() table rows with 500ms interval

The below code fetches a piece of html containing a set number of rows. Some of these rows are of class newentry. ( class="newentry" )
I was expecting my code to display them with 1000m delay, but they all appear simultaneously. Why is the setTimeout not waiting between each call to each rows fadeIn()?
$.ajax({
url: "#{Live.live(event.mnemonic)}",
success: function(data) {
var wait =0;
$("#results").html(data);
wait =500;
$(".newentry").each(function(){
setTimeout(function() { $('#'+this.id).fadeIn(); }, wait);
wait += 1000;
});
}
setTimeout('tick()', 1700-wait);
}
});
Try this
$(".newentry").hide();
$.ajax({
url: "#{Live.live(event.mnemonic)}",
success: function(data) {
$("#results").html(data);
i=500;
$('.newentry').each(function(){
setTimeout(function(){delayedShow($(this))},i);
i=i+500;
});
{
}
});
function delayedShow(obj) { obj.fadeIn(); }

How do I make Ajax update every 10 seconds in jquery?

How do I make Ajax update every 10 seconds in jquery?
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
}
For example I am testing the jquery above to get a RSS feed. So how do you make it update the RSS every 10 seconds so the user can see a new item in the feed?
Creating an interval
var ResInterval = window.setInterval('myAjaxCall()', 60000); // 60 seconds
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
To stop
window.clearInterval(ResInterval);
I'd avoid the synchronous ajax call. It'll make anything else on the page like animations freeze. Of course with asynchronous calls you'll need to make sure they don't start overlapping. In your setInterval you could just put a lock:
var doingAjax = false;
setInterval(function() {
if (!doingAjax) {
doingAjax = true;
jQuery.ajax({
...,
success: function() {
doingAjax = false;
...
}
});
}
};
wrap it in a function and use setInterval()

Resources