Ajax poll request every 10 seconds.

This is a short tutorial on how to send an Ajax request every 10 seconds – something that is often referred to as polling. Obviously, if needs be, you can change the code to send a request every 60 seconds instead. In this article, I will be using the JavaScript library JQuery.

An example of a script that sends an Ajax request every ten seconds:

setInterval(function()
{
    $.ajax({
        type: "get",
        url: "my-script.php",
        success:function(data)
        {
            //console.log the response
            console.log(data);
        }
    });
}, 10000); //10000 milliseconds = 10 seconds

Here, we used theĀ setInterval method to send a simple Ajax GET request every 10 seconds. Note that the setInterval function expects the time in milliseconds. Hence the reason we use 10,000 milliseconds (because 10,000 milliseconds = 10 seconds). If you want the request to be sent every 60 seconds, then you will need to change this value to 60,000.

Note that there is one major drawback to using this approach. If the first request does not finish in time, then the second request will still be sent! i.e. You could potentially find yourself in a situation where requests are queuing up to reach your server.

If you want to make sure that an Ajax request finishes before any further requests are sent, then you will need to be a bit smarter with your approach.

In this example, we will wrap our request in a custom function and use the setTimeout method:

//Our custom function.
function send(){
    $.ajax({
        type: "get",
        url: "test.php",
        success:function(data)
        {
            //console.log the response
            console.log(data);
            //Send another request in 10 seconds.
            setTimeout(function(){
                send();
            }, 10000);
        }
    });
}
//Call our function
send();

In the code above:

  1. We placed our Ajax request inside a custom function called send. You can name this as something else if you wish.
  2. Inside the success function of our Ajax request, we use the setTimeout method. Here, we specify that we want to send another request 10 seconds after the current request has been successfully completed. This means that the script we are sending the request to should only receive 1 request every 10 seconds at most.

Note that you should be careful when implementing Ajax polling as you do not want to be overloading your own server with requests, especially if the script being accessed is resource intensive. If you need your website to display live data, you may want to look into usingĀ WebSockets instead.