Auto Refresh Div Content Using jQuery and AJAX

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.

< ?php
$feed_url = 'http://blogoola.com/blog/feed/';
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
$feedData = '';
$date = date("Y-m-d H:i:s");

//output
$feedData .=  "<ul>";
foreach($x->channel->item as $entry) {
    $feedData .= "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";
}
$feedData .= "";
$feedData .= "<p>Data current as at: ".$date."</p>";

echo $feedData;
?>

Full Code

<html>
<head>
<title>Auto Refresh Div Content Demo | jQuery4u</title>
<!-- For ease i'm just using a JQuery version hosted by JQuery- you can download any version and link to it locally -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
(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);
</script>
</head>
<body>

<div id="wrapper">
    <div id="content"></div>
    <img src="loading.gif" id="loading" alt="loading" style="display:none;" />
</div>

</body>
</html>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Leo anthony

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

  • http://www.flapane.com/ flapane

    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.

    • http://jquery4u.com/ jQuery4u

      Thanks

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

    • http://jquery4u.com/ jQuery4u

      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

  • http://www.mayurgodhani.com/ Mayur Godhani

    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.

    • http://jquery4u.com/ jQuery4u

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

  • http://www.facebook.com/abhinav.moolagundla Abhinav Moolagundla

    is there any way to stop refreshing on a button click

    • http://jquery4u.com/ jQuery4u

      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.