$.ajax({
url: "data.php"
}).done(function(data) {
//code
});
how to wrap this in jQuery timeout function for example send an ajax request every 2 sec.?
$.ajax({
url: "data.php"
}).done(function(data) {
//code
});
how to wrap this in jQuery timeout function for example send an ajax request every 2 sec.?
If you wrap this in a setInterval
, you run the risk of sending your server a ton of requests with the potential of not getting them all back in order. Put a timeout
inside the callback:
function runAjax() {
$.ajax({
url: "data.php"
}).done(function(data) {
//code
setTimeout(runAjax, 2000); //Run it again in 2 sec
});
}
runAjax(); //I suppose we should start the AJAX :D
I would do something like this:
var ajax = null;
function callAjax()
{
if(ajax != null)
ajax.abort();
ajax = $.ajax({
url: "data.php"
}).done(function(data) {
//code
});
setTimeout(callAjax, 1000); // Every 1 second
}
callAjax();
This code will execute the Ajax call once every 1 second. If another request is running, it will kill it before running another one.
A better way would be to use long polling: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
you can use setInterval.
var xhr;
setInterval(
function runAjax() {
if(xhr) {
xhr.abort();
}
xhr = $.ajax({
url: "data.php"
}).done(function(data) {
});
}, 2000
)
try like this.