Show AJAX upload status on progress element

Madara's Ghost picture Madara's Ghost · Aug 13, 2011 · Viewed 88.2k times · Source

I have an AJAX script to upload a file to a PHP script that is likely to take at least 10 seconds to run. I would like to display progress for it for the user.

In the executing class, I have a property $progress which is updated with the progress (in 1-100), and a method get_progress() (which's purpose should be obvious).

The question is, how to update the <progress> element on the front end for the user to see?

I think AJAX is the solution, but I just can not get my head around it. I can not get to the same object instance.

Answer

l0ft13 picture l0ft13 · Mar 16, 2012

I'll put this here as a reference for anyone searching - this relies on no javascript at all..

<?php

/**
 * Quick and easy progress script
 * The script will slow iterate through an array and display progress as it goes.
 */

#First progress
$array1  = array(2, 4, 56, 3, 3);
$current = 0;

foreach ($array1 as $element) {
    $current++;
    outputProgress($current, count($array1));
}
echo "<br>";

#Second progress
$array2  = array(2, 4, 66, 54);
$current = 0;

foreach ($array2 as $element) {
    $current++;
    outputProgress($current, count($array2));
}

/**
 * Output span with progress.
 *
 * @param $current integer Current progress out of total
 * @param $total   integer Total steps required to complete
 */
function outputProgress($current, $total) {
    echo "<span style='position: absolute;z-index:$current;background:#FFF;'>" . round($current / $total * 100) . "% </span>";
    myFlush();
    sleep(1);
}

/**
 * Flush output buffer
 */
function myFlush() {
    echo(str_repeat(' ', 256));
    if (@ob_get_contents()) {
        @ob_end_flush();
    }
    flush();
}

?>