Thursday, March 19, 2009

Partial page refresh with AJAX and JQuery

Problem : mechanism to continuously refresh a web page in order to provide a real-time dashboard of some kind or only could refresh a part of a specific page, for example: the traffic lights on a dashboard that indicate the status of the system.

It is really easy to only refresh a part of the page by using the JQuery JavaScript library. Include the JQuery library into our page, you only need 1 line of JavaScript to get it working:


<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>

<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>

So you just place this little JS code snippet into our page to refresh everything inside the tag with the content id, let’s say every 5 seconds:


setInterval(function() {
$("#content").load(location.href+" #content>*","",);
}, 5000);

setInterval(function() {
$("#content").load(location.href+" #content>*","",);
}, 5000);

That’s it!! It is thus fairly easy to accomplish some real-time monitoring behavior with just that line of code. No more weird meta-refresh tags or iframe kind of workarounds in your web applications.

Every 5 seconds, we will refresh the content of the element with the content of the same URL and all elements that reside under the element with id: content.

JQuery certainly allows you to apply some very powerful techniques in just a few lines of code.