Back to the Konsensys

Back to Tips
Refreshing a Web Page using AJAX
by
George Van Treeck

Sometimes, you have information on your web page that might need to be updated every few seconds or minutes. The usual

<meta http-equiv="refresh" content="60"/>

does not work well with web sites that use the same URL for all web pages by replacing the contents of a page using HTTP POST or AJAX (or both). First, you may only want some pages to be refreshed and not others. Second, a refresh using the method above will most likely take you all the back to first page!

Below is a short snippet of JavaScript code that works for all AJAX-enabled browsers and is used in applications generated the Konsensys DreamBeans tool:

The following can be used to refresh the contents of a web page using AJAX:

    // Initialize specifying NO refresh
    <input type="hidden" id="refresh_rate" value="-1" />>
    // Create a function that uses AJAX to replace the current
    // contents with new contents and set the new refresh rate.
    function my_AJAX(some, args) {
        Click Here for an example.
        ...
        // Clear any previous refresh rate
        if (typeof(top.interval_id) != 'undefined')
            clearInterval(top.interval_id);
        // Get the new refresh rate.
        refresh_rate =
            document.getElementById('refresh_rate').value;
        // The following will call your_function_to_call_AJAX at
        // the specified refresh rate. NOTE the single around
        // the function call...
        if (refresh_rate > 0)
            top.interval_id =
            setTimeout('my_AJAX(some, args)', refresh_rate);
		return false;
    }

To see complete example in use. You can go the website, BestPicker website and view the source HTML.


Copyright (C) 2010 George Van Treeck. All rights reserved.