Leave a comment

Bootstrap Progress bar to show long running PHP script

UntitledWe may have a request to the back end system which may trigger a long running process such as searching huge amount of data or a long running database process. Then the front end webpage may hang and wait for the process to be finished. During this process, if we can provide the user some information about the progress of the back end process, it may improve user experience. Unfortunately, in web applications, this seems not an easy task because web scripting languages don’t support multithreading and HTTP is stateless.  We now can have AJAX to simulate real time process. Today we will use PHP+jQuery to simulate a process to get the progress of a long running process dynamically.

Create progress.php

<?php
 // recommended to prevent caching of event data.
 header('Cache-Control: no-cache');
 session_start();
 $_SESSION['progress_status'] = 0;
 ?>
 <!DOCTYPE html>
 <html>
    <head>
       <title>TODO supply a title</title>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       http://js/jquery.js
       <!-- Latest compiled and minified CSS -->
       <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    
       $(document).ready(function () {
       function getProgress() {
          var random = Math.random(1000);
          $.post('progress_status.php', {random: random}, function (status) {
             var progressBar = $(".progress-bar");
             progressBar.attr('aria-valuenow', status);
             progressBar.css('width', status + '%');
             progressBar.html(status + '%');
             if (status 
    </head>
    <body>
        

Sample Progress Bar

0%
</div>
Start very log task
</div> </body> </html Create progress_start.php
<?php
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
$_SESSION['progress_status'] = 0;
for ($i = 1; $i <= 100; $i++) {
 session_start();
 $_SESSION['progress_status'] = $i;
 session_write_close();
 sleep(1);
}
?>

Create progress_status.php

<?php
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
session_start();
echo $_SESSION['progress_status'];
?>

Leave a comment