jQuery DIV Auto Load and Refresh

jQuery load method requests server pages and refreshes the HTML selector with the page content. In this tutorial, we are going to auto-load and refresh a DIV with a periodic interval.

This jQuery auto load tutorial will help to refresh content with the very latest feeds, load random advertisement banners and etc.

View Demo

jQuery Auto Load

Very few lines of code are required for the jQuery auto load. And it is,

$(document).ready(function() {
	setInterval(function() {
		$("#screen").load('banners.php')
	}, 2000);
});

The PHP file banners.php is requested via jQuery ajax using load method.

jquery-div-auto-load-refresh

This file contains an array of HTML color codes. One of those colors is picked using PHP array rand to change banner backgrounds and loaded into a specified DIV. The PHP code is,

<?php
$bg_array = array(
    "#CEED9D",
    "#ECED9D",
    "#EDCF9D",
    "#EC9CA7",
    "#ED9DD0",
    "#EE9DE2",
    "#D69DEC",
    "#9E9CEC"
);
$bg = array_rand($bg_array, 1);
?>
<div class="banner" style="background-color:<?php echo $bg_array[$bg];?>;" >
	<div class="txt-title">jQuery DIV Auto Load Refresh</div>
	<div class="txt-subtitle">This Banner auto loads and refreshes every 2
		seconds.</div>
</div>

This jQuery load event happens every 2 seconds to update the banner periodically. Instead of using static array data, we can connect DB to load div with dynamic data.

View DemoDownload

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 13, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).
Explore topics
Need PHP help?