Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodically send ajax requests

There is a page and I want periodically to make "background" ajax requests. So the page is loaded then it should send ajax requests in a certain amount of time.

I might use cron for that. I have never use previously so I'm wondering if it would fit for that task. Is there any other more simple way?

P.S. The time delay will be about 5 minutes.

like image 880
Alan Coromano Avatar asked Dec 08 '22 16:12

Alan Coromano


2 Answers

Since there is essentially an unknown delay between the time you send out an AJAX request and the time you receive a complete response for it, an oftentimes more elegant approach is to start the next AJAX call a fixed amount of time after the prior one finishes. This way, you can also ensure that your calls don't overlap.

var set_delay = 5000,
    callout = function () {
        $.ajax({
            /* blah */
        })
        .done(function (response) {
            // update the page
        })
        .always(function () {
            setTimeout(callout, set_delay);
        });
    };

// initial call
callout();
like image 96
Richard Neil Ilagan Avatar answered Dec 11 '22 07:12

Richard Neil Ilagan


Cron is run on the serverside and you are using HTML and AJAX, so you should solve this issue in Javascript :-)

By using something like setInterval you can keep executing a function, your case might be something like polling a url via AJAX:

function updatePage(){
  // perform AJAX request
}
setInterval(updatePage, 5000);
like image 30
Bitterzoet Avatar answered Dec 11 '22 09:12

Bitterzoet