I'm learning jQuery, and I'm trying to find a simple code example that will poll an API for a condition. (ie, request a webpage every few seconds and process the results)
I'm familiar with how to do AJAX in jQuery, I just can't seem to find the "proper" way of getting it to execute on a "timer".
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
Here's a (archive.org mirror of a) helpful article on long polling (long-held HTTP request) using jQuery. A code snippet derived from this article:
(function poll() {
setTimeout(function() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 2000
})
}, 5000);
})();
This will make the next request only after the ajax request has completed.
A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.
(function poll() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})
})();
From ES6,
var co = require('co');
var $ = require('jQuery');
// because jquery doesn't support Promises/A+ spec
function ajax(opts) {
return new Promise(function(resolve, reject) {
$.extend(opts, {
success: resolve,
error: reject
});
$.ajax(opts);
}
}
var poll = function() {
co(function *() {
return yield ajax({
url: '/my-api',
type: 'json',
method: 'post'
});
}).then(function(response) {
console.log(response);
}).catch(function(err) {
console.log(err);
});
};
setInterval(poll, 5000);
function poll(){
$("ajax.php", function(data){
//do stuff
});
}
setInterval(function(){ poll(); }, 5000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With