JavaScript
Article
By Sam Deering

Auto Refresh Div Content Using jQuery and AJAX

By Sam Deering

So today I needed content in a div to refresh every 5 seconds so I decided to do a quick demo to show you how it can be done. It initially loads the content using AJAX shorthand method .load() and then simply sets a recurring call for the data every 5 seconds.

Demo

The demo displays the latest blog posts from the rss feed on my blog and displays the date and time for the latest data refresh. I’ve also hooked up a loading image for the AJAX requests using $.ajaxSetup() but this is optional if you didn’t want to see a loading image you could remove this code or even display a smaller loading image so the data is still visible on screen while the new data is loading asynchronously.

data-refresh-x-seconds2
View Demo

jQuery and AJAX Call Code

(function($)
{
    $(document).ready(function()
    {
        $.ajaxSetup(
        {
            cache: false,
            beforeSend: function() {
                $('#content').hide();
                $('#loading').show();
            },
            complete: function() {
                $('#loading').hide();
                $('#content').show();
            },
            success: function() {
                $('#loading').hide();
                $('#content').show();
            }
        });
        var $container = $("#content");
        $container.load("rss-feed-data.php");
        var refreshId = setInterval(function()
        {
            $container.load('rss-feed-data.php');
        }, 9000);
    });
})(jQuery);

data-refresh-x-seconds

PHP Data Script Code

This PHP script loads the blogs RSS feed and sends back the data along with the current date and time.

";
foreach($x->channel->item as $entry) {
    $feedData .= "
  • " . $entry->title . "
  • "; } $feedData .= ""; $feedData .= "

    Data current as at: ".$date."

    "; echo $feedData; ?>

    Full Code

    
    
    
    • Leo anthony

      Is there a way to catch http request failed error and display custom error message instead of the usual one

    • Thanks a lot, it works great! It helped me because I have to include a php file which sometimes may cause timeouts. If I use your solution, my main page won’t be affected by an eventual timeout.

    • Tamil Melisai

      Could you please help me by looking at the following site:m.tamilmelisai.com.
      I have applied your code but the contents from playing.php file is loading late and suddenly the whole page disappears.

      • If you open the website and take a look at firebug it reports:

        showPicture is not defined

        If you dig deep into the HTTP requests you will find lines in the image HTML which call onload a function called showPicture which doesn’t exist.


        From this HTTP request as an example:
        http://m.tamilmelisai.com/playing.php?_=1340876878100

        You also have a double script tag just before

        You are also missing a close tag at the end of page.

        Hope this helps, without seeing the PHP unable to debug any further.
        Thanks,
        Sam

    • Tamil Melisai

      Appreciate your response and thanks for the hints. I have managed to rectify the errors except just wanted to quote that the “show pic” has the following code:

      picture)) : ?>
      <img id="cpPictureMainSong" onload="showPicture(this, true)" width="80" height="80" src="picture; ?>” />

      Do u reckon this might effect the result of the page.Sorry these codes are original from SAM Broadcaster templates.Let me know if i need to tweak something else and yes thank you for the above tips!!

    • can-inlife

      keep working. thanks

    • Hey mate !!
      Your example is working great !!
      Still i have two questions !!!
      1) is it supports multiple blog rss feeds ? (e.g; i own three blogs, can i display all its update on one feed ?)
      2) I want to remove Loading image, which displaying after each 5 seconds. is there any solution like this ? fade in top newest item and exactly fadeout one old item from the list ?.

      I am not freak in Jquery and AJAX :( so please guide me.

      • Hi Mayur,

        1. Sure, you can add as many feeds as you like, just put them in the PHP file: rss-feed-data.php have that return a mixture of results from your 3 blogs.

        2. You can remove the loading image by removing the $(‘#loading’).show(); code from the ajax setup function. As for loading in new feeds from the top you would have to change the PHP script to return JSON (use json_encode on a PHP array) then write some JS code to process through the feeds and create a front end cache which you could compare then fade in the new feeds into the top. When I get the chance I’ll code a demo for this, busy on the new blog design atm! :)

        Cheers,
        Sam

        • Merkel

          How can I add multiple feeds in the rss-feed-data.php? I tried to use a comma and didnt work…e.g.: $feed_url = ‘feed1′,’feed2’;

    • Jayant Patil

      Its nice…… I like it Thanks Sir..

    • is there any way to stop refreshing on a button click

      • Hi Abh,

        You can cancel the refresh anytime by clearing the setInterval like so:

        clearInterval(refreshId);

        Just attach that to a button or call from within a function which is event based.

        Cheers,
        Sam

    • Kiel

      Is this server healthy?

    • yakub

      this is great, i was looking for such code from many days. Thank you very much.

      • ssds

        sdsd

        • sds

          sdssd

          • sdfsd

            sdsfd

            • ss

              ssss

            • s

              ssssss

            • s

              ewe

    • Johnny

      Hi, this code is great! How do I refresh more than one div on the same page?

    • Kalyan N

      Hi it was usefull but i have a question..
      1. some stock market website page display the stock market updates.. i want to display the updates they do every 5 mins in my page can i do it using the method u have done..?
      2. i just need part of feed like only the stock market ticker which updates every second in those websites.

    • Is this anything wrong? Why this code won’t work in Chrome?

    • Mihai

      Hello. Thanks a lot for your code. It works great. I am using it to refresh the data from a MySql database.

      However, is there any possibility to refresh the page only if a change has made ( in my case in the database ). That way, the page will not blink every time, only when the information to display has changed.

      Thanks !

    • TechVivek

      It is not working
      My Code

      (function($)
      {
      $(document).ready(function()
      {
      $.ajaxSetup(
      {
      cache: false,
      beforeSend: function() {
      $(‘#content’).hide();
      $(‘#loading’).show();
      },
      complete: function() {
      $(‘#loading’).hide();
      $(‘#content’).show();
      },
      success: function() {
      $(‘#loading’).hide();
      $(‘#content’).show();
      }
      });
      var $container = $(“#content”);
      $container.load(“home.php”);
      var refreshId = setInterval(function()
      {
      $container.load(‘home.php’);
      }, 9000);
      });
      })(jQuery);

      posted <?php echo " $posts ” ?>

      posted <?php echo " $postvivek ” ?>

      Please tell me the problem of this code

    • Andra

      tanks.
      It is work

    Recommended
    Sponsors
    Get the latest in JavaScript, once a week, for free.