jQuery progress bar
Very often we want to check the progress with the server while waiting for an output.
Assume the server has an endpoint /progress for checking status, and we want to check the status every 5 seconds and update a progress bar / display text.
The below update_progress function simply 'get' data from /progress endpiont and display it as text on the 'message' element (a div or any thing). The trick is the setTimeout function which calls the update_progress function itself again after 5 seconds. In this way it is like a loop running the 'get' every 5 seconds. But you will need some protocol to quit the loop (missing in the example here), e.g. if data is 'END' then skip the setTimeout so it will quit.
<script>
$(function() {
$('#submitfile').click( function(){
update_progress()
} ) } );
function update_progress(){
$.get( "/progress", function( data ) {
if(data != ""){ $("#message").text(data) }
setTimeout(update_progress, 5000)
} )}
</script>
You may also want something more fancy than simply displaying the progress as a text element. E.g. a progress bar.
Below is an exmaple, you need the jquery-ui.js library. Simply define a div element as the progress bar, and initiate it using the $( "#progressbar" ).progressbar({value: 0 }); The initial value is 0, the default range is 0-100.
<html ><head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#progressbar" ).progressbar({
value: 0
});
} );
</script>
</head><body>
<div id="progressbar"></div>
</body></html>
Now if you want to update the progress bar, in the obove update_progress function, you may simply get or set the value by:
// Getter
var value = $( ".progressbar" ).progressbar( "option", "value" );
// Setter
$( ".progressbar" ).progressbar( "option", "value", 25 );
Now you want to display the progress bar only when a certain button is clicked intead of showing it all the time. You may set the css style to 'display:none' so it won't display.
<div id="progressbar" style="display:none"></div>
When a submit button is clicked, dynamically change the css style to "display:block" so it will display.
$('#submitfile').click(
function(){
if($("#progressbar").css("display")== "none"){
$("#progressbar").css("display", "block")
}} )
Simply combine the above snippets.