Total used files :

  • index.php
  • jquery.js
  • random.php

I am using jQuery's setInterval() method to automatically make the ajax call in every 2 seconds.

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
 <head>  
 <title>Refresh Page itself</title>  
 <script type="text/javascript" src="jquery.js"></script>  
 <script>  
 $(document).ready(function(){  
     var callAjax = function(){  
         $.ajax({  
             method:'get',  
             url:'random.php',  
             success:function(data){  
                 $("#sample").html(data);  
             }  
         });  
     }  
     setInterval(callAjax,2000);  
 });
 </script>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
 </head>  
 <body>  
     <?php  
         print "Below number changes in 2 seconds interval, View-Source of this page to see the usuage of jquery for content refresh.<div id=’sample’>100 </div>";  
     ?>  
 </body>  
</html>  

In above code, the interesting code is in line 17,

setInterval(callAjax,2000);

which calls the callAjax function in every 2 seconds. Here 2000 is supplied in milliseconds.

line 11 – sets the url to “random.php”

line 13 – replaces the #sample div with the response from the “random.php” file that is the output of

print 5*rand(1,100);

And this is the code for “random.php” that is called by ajax call in every 2 seconds.
random.php

<?php  
print 5*rand(1,100);  

You can test the demo online at http://www.samundra.com.np/refresh/