A progress bar indicates the status of a work in progress. If some process or task takes a long time to complete, an indication of the completion status, to a waiting user, is always helpful. A simple progress bar can be displayed using the jQuery Progress Bar UI.
If we take a look at the source code of the jQuery Progress Bar, we will notice, that the value of the progress bar is updated after static intervals, triggered by the jQuery’s setTimeout() function.
In other words, this indicates that the progress bar will be set to complete after a certain interval, irrespective of the fact that the actual task is completed or not.
Hence, if to indicate the actual completion status of a task in progress, we would have to dynamically retrieve the status of the task, and set the values for the progress bar.
How to Change the Progress Bar values Dynamically?
Consider that you have a task in progress, such as a page being loaded, content being downloaded, etc. If you wanted to display a real time progress bar for the task, you will need to do the following:
Send a Timely Status Update
The task in progress has to schedule a timely status update. This value would be used to update an option in the database. For example,
// set the task status, e.g., In Progress, Validating, Completed
// set the percentage completed
where ‘Validating data’ and ‘75’, are an indication of the task activity and the percentage complete respectively.
Reading these values, would give us an indication of the task status.
Fetching the Status Values
After specific time intervals, we can fetch the values of the database option (task status), using AJAX calls. These can be used to set the progress bar values, to give an actual indication of the progress status. We need to retrieve the two values, the percentage complete (wdm_task_status_value) and the status text (wdm_task_status_text). This can be done as follows:
$status = get_option(‘wdm_task_status_value’);
$status_text = get_option(‘wdm_task_status_text’);
echo $status . “|” . $status_text;
We can now update the Progress Bar functions, using the above retrieved values.
Updating the Progress Bar Status
The values can be received in the AJAX response, and can be used as follows:
var pos = data.indexOf(‘|’);
var text = data.substr(pos+1);
var status = data.substr(0,pos);
var val = parseInt(status);
progressbar.progressbar( “value”, val);
where data, is the result of get_progressbar_status function, and will be in the form of status|status_text.
Thus, by making this simple change you will be able to create a dynamically updating jQuery progress bar, for your task in progress.