Automatically refresh div after n number of seconds

Some time we required this feature in our website to display some real time data on a div container, For doing this we need to update/refresh div content after each n number of seconds without refresh the whole page.

So in this tutorial i am going to show you how can you refresh any div box in n number of seconds with updated information.

For example you might have seen in facebook or twitter shows new news feed updates on top of the page after certain time period so if you are planning to create this type of feature in your website then it must help you to do the same.


Suppose you have a separate page where you are displaying new post “new_post.php”;

You have to load this page on your landing page “index.php” and should refresh every 5 second then your code will be.

index.php

 <div id="newpost"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
 $(function() {
  function newPost() {
      $("#newpost").empty().load("new_post.php");
   }
    var res = setInterval(newPost, 5000);
 });
</script>

Where setInterval(“YOUR_JAVASCRIPT_FUNCTION”, milliseconds);

The above code refresh newpost div every 5 second and display latest post on your landing page. you can also pass the parameter to handle request like

 $("#newpost").empty().load("new_post.php?limit=5");

You can also use jquery $.get, $.post and $.ajax function for doing the same task and catch the response in div container.

If you want to stop refreshing div at any time then you can use clearIntereval() function in javascript.

<script>
 $(function() {
  function newPost() {
      $("#newpost").empty().load("new_post.php");
   }
    var res = setInterval(newPost, 5000);
 });
 
 function stopAutoRefresh() {
  clearInterval(res);
}
</script>

Where clearInterval(“SETINTERVAL_ID”);
Call stopAutoRefresh function on any event when you required to stop refreshing div.

cheers 🙂