Send AJAX request every n seconds using jQuery

By informerfrk

AJAX stands for Asynchronous JavaScript And XML. You can see lots of modern websites are using AJAX.

AJAX is awesome as it does not need to refresh the whole page to load something on a web page. previously I have also discussed on AJAX on this post – Process form value in PHP using jQuery AJAX method. Here is another post related to jQuery AJAX – AJAX search from MySQL database in PHP example.

In this post, I am going to tell you how to execute or send AJAX request in every n seconds. In many modern websites, you can see this functionality.

AJAX search from MySQL database in PHP example

Process form value in PHP using jQuery AJAX method

For example, on Facebook, you see the online friend list is automatically updating, automatically you got the message after you receive a new message and the same thing also happen when you get new mail on Gmail default view.

You may think how all these things happening without doing anything. Surely, they are using AJAX. But how these AJAX request call without doing anything, like you, didn’t click on any button or anywhere and still the new message is coming, online friend list updating.

How to send email using PHP mail() function?

Well, these things are happening by sending an AJAX request every particular time. After a certain time interval, the AJAX call occurs. It can be easily done by using jQuery AJAX.

Here in this example, I am going to give you a simple example code snippets of jQuery AJAX that can execute AJAX in every 5 seconds. We are going to use the setInterval JavaScript method. Using setInterval() method we can do the task easily.

The jQuery code to call AJAX in every 5 seconds

Here is the jQuery code:

$(document).ready(function(){

  sendRequest();

  function sendRequest(){
      $.ajax({
        url: "<?php echo base_url('loadajax.php'); ?>",
        success: 
          function(data){
           $('#listposts').html(data); //insert text of test.php into your div
           
        },

        complete: function() {
       // Schedule the next request when the current one's complete
       setInterval(sendRequest, 5000); // The interval set to 5 seconds
     }

    });

  };

});

You can see in the above code that we have created a method sendRequest() and than apply the setInterval() method on that sendRequest method.

Now the code will be used to send AJAX request in every 5 seconds. The time interval 5000 refers to micro seconds.You can use the same code anywhere where you want to request AJAX call in every n

You can use the same code anywhere where you want to request AJAX call in every n seconds. Just replace the time interval with the time that you need in micro seconds.

Leave a Reply

Your email address will not be published. Required fields are marked *