Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute an Ajax request every second [duplicate]

Tags:

jquery

ajax

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     

            }
    });
like image 538
Code_Ed_Student Avatar asked Dec 04 '13 09:12

Code_Ed_Student


People also ask

How do you send AJAX request every 5 seconds?

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.

How do I stop multiple AJAX calls from repeated clicks?

}); 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.

Does AJAX follow redirect?

ajax appears to always follow redirects.

Can AJAX requests be made synchronous?

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.


1 Answers

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.

like image 60
T.J. Crowder Avatar answered Oct 15 '22 16:10

T.J. Crowder