Execute an Ajax request every second

Viewed 54621

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     

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

Something you might want to consider is Server Sent Events (SSE's)

This is an HTML5 technology whereby Javascript will "long-poll" a server endpoint (your PHP file) to see if any changes have occurred. Long-polling is basically where JS (I'm not sure if it uses Ajax or another technology) sends a request every second to the endpoint

You can try it like this:

#/your_js
var evtSource = new EventSource("increment.php");
evtSource.onmessage = function(e) {
    $('#hidden').val(e.data);
}

To send the data, you can make an ajax call which will send the updated JSON object to the server, like you have:

  $(document).on("click", ".your_object", function(data) {
     $.ajax({
                type: 'POST',
                url: 'increment.php',
                data: $(this).serialize(),
                dataType: 'json'
        });
   });

This will only open an Ajax request when you perform an event, and your app will be "listening" for the response every second. As you are aware, Ajax long-polling is super resource-intensive, so it will be better to look at web-socket stuff if you want true "real-time" technology, but either way, this will be a much more efficient system than just using plain ajax for everything

A caveat here -- you'll have to change your increment.php to handle the different response types

Yes possible using setInterval

1) Keep your ajax within a function.

function fun() {
$.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                    $('#hidden').val(data);// first set the value     

            }
    });
}

2) Now using setInterval, you can execute it every second.

var interval = setInterval(fun, 1000);

3) To pause/clear use clearInterval

clearInterval(interval);

4) As other pointed that using setInterval for ajax is not wise, so try using

var interval;
function callAjax() {
  $.ajax({
                type: 'POST',
                url: 'increment.php',
                data: $(this).serialize(),
                dataType: 'json',
                success: function (data) {
                        $('#hidden').val(data);// first set the value 
                        interval = setTimeout(callAjax, 1000);   
                }
        });
}
callAjax();
//clearTimeout(interval);
Related