JavaScript - - By Sam Deering

Auto Refresh Div Content Using jQuery and AJAX

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

    
    
    
    Sponsors