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.


<!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.

print 5*rand(1,100);

You can test the demo online at

Samundra Shrestha

I work as fullstack developer. Having spent more than 5 years in the web development technologies, I aspire to create an environment where we can share, learn and grow together.

3 thoughts on “Automatic ajax call using jQuery

  • April 1, 2017 at 6:14 AM

    i want redirect a page automatically after form submission. how can i do this.
    thank u

    • May 17, 2017 at 4:57 PM

      Hi Divya,

      You can use javascript and use window.location to redirect user to different location.

  • September 25, 2016 at 2:02 AM

    I appreciate, lead to I discovered exactly what I was taking a look for.
    You have ended my 4 day long hunt! God Bless you man. Have a
    nice day. Bye


Leave a Reply

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