Occasionally it is useful to silently load content into an area on a webpage. For example, you may have a list of recent comments that you want to refresh every minute. Using a meta refresh is one option, but this would cause the whole page to refresh, which could annoy the user. The solution is Ajax, where I’ll reload the content silently without a single page refresh. Even writing the simplist of Ajax functions is quite painful and requires a fair few lines of code to get things done. To make things simpler we’ll use my favourite JavaScript Framework, JQuery.
The plan is to have dynamic content loaded via Ajax and refresh every x seconds. We’ll also have a loading image to show the user something is actually happening behind the scenes, as having nothing while the content is loading could make the user leave. The latter is especially important when querying large sets of data, where a delay is possible. You can get your own loading images from the ajax loading image site.Now we have a plan, we’ll get right into it.
First course of action is to setup our basic html page. It’s nothing amazing, simply a centered divider with a seperate divider for the loading graphic. Here’s the code we’ll be using (for simplicity I’ve used the style tag for the css, as opposed to having a seperate css file:
<!-- body, h1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 0.8em; } a { text-decoration: none; color: #333; } a:hover { color: #ff0000; } #ajax-content { height: auto; width: 400px; border: 5px solid #ccc; margin: 0 auto; padding: 10px; } #loading { width: 66px; margin: 0 auto; } --> <script src="jquery-1.2.3.min.js" type="text/javascript"></script> <div id="loading"> <img src="loader.gif" alt="content is loading" width="100" height="100" /> </div>
The JQuery library has also been included in the header – you can download JQuery from the official site. Our actual content will be loaded into the div called ‘ajax-content’. For the content I’ve simply used an external php file that echos an un-ordered list and the current server time (you can then see that the content has been refreshed as the time changes). This has been done for simplicity, but you could easily query a database for information. PHP’s sleep function was used to create a delay when loading the content, this way you can see something is actually happening. In reality you would never want to use sleep, as it simply delays loading times. The contents of the PHP file are as follows:
Last Updated: ".date('h:i:s A').""; echo " <h1>Big List of Software</h1> "; echo " <ul> <li><a href="http://link.com">RmBarCode 1.00a</a></li> <li><a href="http://link.com">ServerMask 3.0.4</a></li> <li><a href="http://link.com">LinkDeny 1.1.0</a></li> <li><a href="http://link.com">Drag Racer 1</a></li> <li><a href="http://link.com">Method123 Educational 3.6</a></li> <li><a href="http://link.com">Easy St. Tycoon 1.0</a></li> <li><a href="http://link.com">iColorPicker 6.18</a></li> <li><a href="http://link.com">USB Virus Scan 2.3</a></li> <li><a href="http://link.com">AWP Light FREE 2.0</a></li> <li><a href="http://link.com">ZipEnable 3.0.2</a></li> <li><a href="http://link.com">w3compiler 1.1.2</a></li> <li><a href="http://link.com">Remote Reboot 2.0</a></li> <li><a href="http://link.com">Pixeur 2.9.0.15</a></li> <li><a href="http://link.com">Mailing Master 2.0</a></li> <li><a href="http://link.com">Rewards Multiply 2.0</a></li> </ul> "; ?>
Now enters the magic, the JQuery. The following code is placed in script tags in the document head, I’ll explain line by line how this works.
function fetchAjaxContent() { var numRand = Math.floor(Math.random()*101); $('#ajax-content').load('ajax.php?UID=' + numRand); }
For simplicity I’ll add a generic function that load’s the contents of our PHP file (ajax.php) via Ajax. This simply uses JQuery’s load function to load the contents of ajax.php. The random number is placed in the querystring to stop Internet Explorer caching the results. The latter could also be done server side via adding the below to ajax.php:
header("cache-control: no-cache");
The following code is placed inside JQuery’s document ready function. Firstly we hide the divider that will contain the ajax content. using more of JQuery’s built in ajax function, I use the ajaxStart function (that is executed whenever an AJAX request begins and there is none already active). In this instance the loading image is simply displayed. The opposite function used is ajaxStop (executed whenever all AJAX requests have ended) to hide the loading image and show the loaded content. Finally, we’ll call our function from previously, ‘fetchAjaxContent()’ from within the JavaScript setInterval function (calls a function at specified intervals in milliseconds, every 5 seconds is used in this example). The complete code for the document ready looks like this:
$(document).ready(function() { $('#ajax-content').hide(); $("#loading").ajaxStart(function(){ $('#ajax-content').slideUp(); $(this).show(); }); $("#loading").ajaxStop(function(){ $(this).hide(); $("#ajax-content").slideDown(); }); setInterval("fetchAjaxContent()", 5000); });
That’s it basically. You can now view a working example or download the source files. Notice how after each refresh, 5 seconds has elapsed in the printed output.
Thanks for reading!
This is awesome, one question, how could you make it so the content is loaded as soon as the page loads, at the moment it has to wait for the interval time to elapse, i want to have my interval at 1 minute but want it to load the content right away then every 1 minute after. Possible?
Many thanks
Hi,
You could just load the content as normal on the page in your server side script. Then use setTimeout as normal – E.g. every x seconds.