Popular posts

Pages

Sunday, July 28, 2013

Autorefresh page (or form submission) using jQuery

In this post you'll see how 'auto-refresh' feature can be put in a web-page (JSP here) or a form submission.

HTML
<span id="spanautorefresh">Refresh in:&nbsp;<label id="clock"></label>&nbsp;</span>

Above HTML is placed in some part of the page for user to know when the page is going to refresh. We'll use the 'clock' label to display remaining seconds to refresh.

jQuery
In our $(document).ready(function(){});, we'll put our jquery function which goes like below

// base functionality start
    var refresh=false;
    var refreshinterval=parseInt(60);
    clock = $("#clock").text(refreshinterval);


    var refreshfn = function autorefresh() {
        if(refresh) {
            var sec = parseInt(clock.text());
            sec = sec - parseInt(1);
            clock.text(sec);
            if(sec<1) {

              clock.text(refreshinterval);
              makeRequest();
              //window.location.reload();
            }
        }
    }; 


setInterval( refreshfn, 1000);

// base functionality ends


//Below 'click' handle is to 'pause' the timer
    $("#spanautorefresh").on('click',function() {
        if(refresh) refresh=false; else refresh=true;
    });


Now lets go through the code. First two lines are used to set the variables for status (refresh=false) and refreshInterval (in our case 60 seconds). Next we're storing the 'clock' label in clock variable for future use. The actual magic is done by the variable 'refreshfn', which is our function. Since we've set the refresh variable as 'false', as the page loads for the first time the timer is off. Once the user clicks on the span (which houses clock) the refresh variable is set to true.
The function 'setInterval( fn_name, milliSeconds ) is standard JS function which invokes the fn_name every milliSeconds ms. In our case it invokes refreshfn every 1000 ms or 1s. When this happens refreshfn is called and if refresh is 'true', the value of clock is reduced by 1. The IF block inside refreshfn checks the text value and if it is less than 1, a> sets the clock text back to 60, and b> calls makeRequest() function in this case. For standard auto-refresh, simply call the window.location.reload() JS function. In this case makeRequest() is doing jquery AJAX/POST request, sending a form data to page X and getting some values to populate a DIV element in current page.

Auto refresh can also be enabled in standard JSP using response headers. But jquery gives you much more control over the functionality and can be triggered by user's action and page state.

I hope you find this functionality useful and easy to implement!