AJAX progress bar

With few lines of JavaScript and CSS it’s possible to make simple AJAX progress bar. JavaScript will periodically ask for progress value and server will respond with JSON data. Progress value is being read and displayed as DIV element width. To start progress bar demo, click on Start button and wait few seconds to begin. To watch how this page sends requests to Web server just open DOM inspector “Network” card.

 


More precisely, every 1000ms sendRequest() method sends request to server – see setInterval line in pollingStart() method. ajax-progress-bar.php responds and requestHandler() processes received JSON data. Progress value in JSON data has meaning of job completion (in percentage).

In following JavaScript source, please focus on sending and handling requests. Property onreadystatechange is function that receives server feedback. It’s important to note that feedback function must be assigned before each send, because after request is completed, onreadystatechange property is cleared.

// create redips container
let redips = {};

// initialization
redips.init = function () {
    // set reference to the progress bar DIV
    redips.div = document.getElementById('progress');
    // create XML HTTP request object
    redips.xhr = new XMLHttpRequest();
    // set interval ID to false
    redips.intervalID = false;
};

// send request to server
redips.sendRequest = function () {
    let numberMax = 20, // limit number of requests (needed only for demo)
        xhr = redips.xhr;
    // if server is asked less than numberMax
    if (redips.number < numberMax) {
        xhr.open('GET', 'ajax-progress-bar.php', true); // open asynchronus request
        xhr.onreadystatechange = redips.requestHandler; // set request handler
        xhr.send(null);                                    // send request
        redips.number++;                                // increase counter
    }
    // otherwise stop polling
    else {
        redips.pollingStop();
    }
};

// request handler
redips.requestHandler = function () {
    let xhr = redips.xhr;
    // if operation is completed (readyState === 4)
    if (xhr.readyState === XMLHttpRequest.DONE) {
        // if HTTP status is OK
        if (xhr.status === 200) {
            // get progress level from JSON output
            let level = JSON.parse(xhr.responseText).progress;
            // set progress bar width and innerHTML
            redips.div.style.width = redips.div.innerHTML = level + '%';
        }
        // if request status is not OK
        else {
            redips.div.style.width = '100%';
            redips.div.innerHTML = 'Error:[' + xhr.status + ']' + xhr.statusText;
        }
    }
};

// button start
redips.pollingStart = function () {
    if (!redips.intervalID) {
        // reset number of requests
        redips.number = 0;
        // start polling
        redips.intervalID = window.setInterval(redips.sendRequest, 1000);
    }
};

// button stop
redips.pollingStop = function () {
    let xhr = redips.xhr;
    // abort current request if status is 1, 2, 3
    // 0: request not initialized
    // 1: server connection established
    // 2: request received
    // 3: processing request
    // 4: request finished and response is ready
    if (xhr.readyState > 0 && xhr.readyState < 4) {
        xhr.abort();
    }
    window.clearInterval(redips.intervalID);
    redips.intervalID = false;
    // display 'Demo stopped'
    redips.div.style.width = '100%';
    redips.div.innerHTML = 'Demo stopped';
};

// add onload event listener
if (window.addEventListener) {
    window.addEventListener('load', redips.init, false);
}
else if (window.attachEvent) {
    window.attachEvent('onload', redips.init);
}

Here you can see ajax-progress-bar.php source (how job progress is emulated). In your case you will have to calculate percentage of completion and return it in JSON format. Caching for ajax-progress-bar.php should be disabled. Many proxies and clients can be forced to disable caching with “header” lines pragma, cache-control and expires.

<?php
// no cache
header('Pragma: no-cache');
// HTTP/1.1
header('Cache-Control: no-cache, must-revalidate');
// date in past
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// prepare demo progress value
$progress = (time() % 50) * 2;
// return progress level in JSON format
print "{\"progress\": \"$progress\"}";
?>

Download source code: redips6.tar.gz

11/21/2010 – Code tested with JSLint & enabled source download
06/10/2011 – Added limit of how many times to request the server (automatic demo stop)
26/03/2020 – Code tested with ESLint & changed to use JSON instead of XML

64 thoughts on “AJAX progress bar”

  1. Seeing the actual code in your /my/ajax-progress-bar.php would complete this example. Otherwise it’s left to the imagination as to how your process produces that XML doc.

  2. @roger – Last listing in post is actually the source of the ajax-progress-bar.php used in this demonstration. It hasn’t much sense, but it good enough for demo. ;)

  3. could you use this for an upload progress bar? if so, what parameters do I change?

  4. Can you tell me how can I implement the php part in C. I am developing an Ajax based file upload progress bar and if i use text file to update data at server end, then progress bar is not updated as expected as Ajax is not able to read the updated values when the file is being updated. Any idea how to implement this in C based CGI.

  5. It’s very good.
    I like this.
    Thanks for share.
    And I wrote something to introduce this project for my readers.
    You can find the post about this in my website.
    If something is wrong,pls figure it out.thanks.

  6. Very nice code, thank you.

    How do I make to stop it automatically whenever it reaches 100% ?

    best regards and thank you
    Pepe

  7. @Pepe – You can modify code inside if (request.status === 200) to look like this:

    if (request.status === 200) {
        // get progress from the XML node and set progress bar width and innerHTML  
        level = request.responseXML.getElementsByTagName('PROGRESS')[0].firstChild;  
        progress.style.width = progress.innerHTML = level.nodeValue + '%';
        // if progress bar value reaches threshold 98  then stop
        if (parseInt(level.nodeValue) >= 98) {
            progress.style.width = progress.innerHTML = '100%';
            polling_stop();
        }
    }
    

    For this example I defined threshold of 98% to stop because PHP page never return 100. Hope this will help. Cheers!

  8. hey,
    I want to adapt your progress bar to show me the progress of a large mysql query,
    can you give me any tips?

  9. @razvan – If the main script takes time to execute the full code, you can have some break ups (landmark points) at some intervals (simple scenario is with insert or update in loop). In this intervals you can write/update progress information to the database. Next, ajax-progress-bar.php will simply read progress information and return current job progress to show percentage of job done. I think this will work …

  10. @kanmani – You have to create ajax-progress-bar.jsp page that will return simple XML with progress value. And next, in send_request() JavaScript function change URL to point to the JSP page. Please try to click on ajax-progress-bar.php to see a XML format used in this example. Your JSP page should produce the same XML format.

  11. When I run this script, it loads another instance of my CGI program every second as opposed to getting the status of the already running program.

    What am I doing wrong?
    My CGI is just returning STDOUT text.
    my request_handler looks like this:

    function request_handler() {
        var r = "";
        if (request.readyState === 4) {   // if state = 4 (operation is completed)
            if (request.status === 200) { // and the HTTP status is OK
                r = request.responseText;
                delayWrite(r);
            } else { // if request status isn't OK
                r = request.responseText;
                delayWrite(r);
            }
        }
    }
    
  12. @Shawn – So, you started some job from browser and want to follow progress of execution. That’s fine, but don’t forget that HTTP is stateless protocol. In other words, HTTP server will imply every AJAX request as separated request. OK, imagine your CGI processes heavy job you want to monitor. When a new AJAX request comes to the HTTP server, a single control process of HTTPD (the parent) will transfer that request to the first free child process. So, a new CGI process will get AJAX request – not the previous one that still executes heavy task.

    If you can somehow read the progress of job execution with separate CGI, that should be the solution for your problem.

    I will give you another scenario for monitoring 10000 inserts to the MySQL database. First I have to be sure that execution time will not be longer then PHP limit (or I will have to increase max_execution_time parameter in /etc/php.ini file). Next, after every 100 inserts in table “A”, I will update counter in the same MySQL database (for example “counter” row in my “progress” table). AJAX progress bar will be directed to read the “counter” row from “progress” table and display it to the user interface. With this solution, I will be able to monitor MySQL insert progress …

    Hope this comment will give you some hints and directions.
    Cheers!

Leave a Comment