Automatic ajax call using jQuery

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.

[sourcecode language=”php” highlight=”11,13,17″]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>Refresh Page itself</title>
<script type="text/javascript" src="jquery.js"></script>
var callAjax = function(){
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
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>";

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


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.
[sourcecode language=”php”]
print 5*rand(1,100);

You can test the demo online at