Auto Refresh Div Content Using jQuery and AJAX

Share this article

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="https://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>

Frequently Asked Questions (FAQs) about Auto-Refreshing Div Content with jQuery and AJAX

How can I prevent the page from jumping to the top when the div refreshes?

To prevent the page from jumping to the top when the div refreshes, you can use the ‘preventDefault()’ method in jQuery. This method stops the default action of an element from happening. For example, it can prevent a link from following the URL. Here’s how you can use it:

$("#yourDiv").click(function(e){
e.preventDefault();
// Your AJAX call here
});
In this code, ‘e’ is the event object, which contains information about the event.

Can I use AJAX to refresh multiple divs at once?

Yes, you can use AJAX to refresh multiple divs at once. You just need to make separate AJAX calls for each div. Here’s an example:

$.ajax({
url: 'your_url',
success: function(data) {
$('#div1').html(data);
}
});

$.ajax({
url: 'your_url',
success: function(data) {
$('#div2').html(data);
}
});
In this code, ‘#div1’ and ‘#div2’ are the IDs of the divs you want to refresh.

How can I refresh a div after a specific time interval?

You can use the ‘setInterval()’ method in JavaScript to refresh a div after a specific time interval. This method calls a function or evaluates an expression at specified intervals (in milliseconds). Here’s how you can use it:

setInterval(function() {
$("#yourDiv").load(location.href + " #yourDiv>*", "");
}, 5000);
In this code, ‘5000’ is the time interval in milliseconds (5000 milliseconds = 5 seconds).

How can I stop the div from refreshing?

You can stop the div from refreshing by clearing the interval. You can do this using the ‘clearInterval()’ method in JavaScript. Here’s how you can use it:

var interval = setInterval(function() {
$("#yourDiv").load(location.href + " #yourDiv>*", "");
}, 5000);

// To stop the div from refreshing
clearInterval(interval);
In this code, ‘interval’ is the variable that stores the interval ID.

Can I use AJAX to refresh a div without jQuery?

Yes, you can use AJAX to refresh a div without jQuery. You can do this using the ‘fetch()’ function in JavaScript. Here’s how you can use it:

fetch('your_url')
.then(response => response.text())
.then(data => {
document.getElementById('yourDiv').innerHTML = data;
});
In this code, ‘your_url’ is the URL you want to fetch data from, and ‘yourDiv’ is the ID of the div you want to refresh.

How can I handle errors in AJAX?

You can handle errors in AJAX by using the ‘error’ callback function. This function is called if the request fails. Here’s how you can use it:

$.ajax({
url: 'your_url',
success: function(data) {
$('#yourDiv').html(data);
},
error: function() {
alert('An error occurred');
}
});
In this code, the ‘alert()’ function is called if the request fails.

Can I refresh a div when a button is clicked?

Yes, you can refresh a div when a button is clicked. You can do this by attaching a click event to the button. Here’s how you can do it:

$('#yourButton').click(function() {
$.ajax({
url: 'your_url',
success: function(data) {
$('#yourDiv').html(data);
}
});
});
In this code, ‘#yourButton’ is the ID of the button.

How can I pass data to the server in an AJAX call?

You can pass data to the server in an AJAX call by using the ‘data’ option. This option allows you to specify data to be sent to the server. Here’s how you can use it:

$.ajax({
url: 'your_url',
data: {
key1: 'value1',
key2: 'value2'
},
success: function(data) {
$('#yourDiv').html(data);
}
});
In this code, ‘key1’ and ‘key2’ are the keys, and ‘value1’ and ‘value2’ are the values.

Can I use AJAX to refresh a div with a specific class?

Yes, you can use AJAX to refresh a div with a specific class. You just need to replace the ID selector with the class selector. Here’s how you can do it:

$.ajax({
url: 'your_url',
success: function(data) {
$('.yourClass').html(data);
}
});
In this code, ‘.yourClass’ is the class of the divs you want to refresh.

How can I refresh a div without reloading the page?

You can refresh a div without reloading the page by using AJAX. AJAX allows you to update parts of a web page, without reloading the whole page. Here’s how you can do it:

$.ajax({
url: 'your_url',
success: function(data) {
$('#yourDiv').html(data);
}
});
In this code, ‘your_url’ is the URL you want to fetch data from, and ‘#yourDiv’ is the ID of the div you want to refresh.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQueryrefresh rss feed every 5 seconds
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form