I have an ajax call being made to a php file. I am receiving results. Now I am investigating if it is possible to have the ajax request automatically perform every 1 second. I am posting the results into input field called hidden
. How can I execute the ajax call every three seconds without having to call the function?
$.ajax({
type: 'POST',
url: 'increment.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#hidden').val(data);// first set the value
}
});
Creating a function that calls the AJAX request and using this function in setInterval() and set Interval for 5 sec. Now the function executes every 5 seconds and fetches new data from the server. It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.
}); If isLoading is false, the AJAX call starts, and we immediately change its value to true. Once the AJAX response is received, we turn the value of that variable back to false, so that we can stop ignoring new clicks.
ajax appears to always follow redirects.
AJAX can access the server both synchronously and asynchronously: Synchronously, in which the script stops and waits for the server to send back a reply before continuing. Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.
You can do this with a repeated series of setTimeout
calls. (Don't use setInterval
with ajax
calls, you'll get chaos in no time; setInterval
will fire off the next ajax call even if the previous one hasn't completed yet.)
Use setTimeout
to schedule the first call, and then when it completes to schedule the next, etc.:
var interval = 1000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
$.ajax({
type: 'POST',
url: 'increment.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#hidden').val(data);// first set the value
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
Note that I'm using complete
, not success
, to schedule the next call, so that an interruption (temporary drop in your 'net connection, whatever) doesn't kill the process.
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