Home >Backend Development >PHP Tutorial >How can AJAX be used to display real-time progress for file uploads?
AJAX Progress Bar for File Upload Status
A file upload task may often involve a significant processing time, making it imperative to provide the user with progress updates. An AJAX script can fulfill this requirement by providing real-time progress information.
AJAX Implementation
In the provided example, the executing class has a $progress property that holds the upload progress (1-100) and a get_progress() method for retrieving it. To display this progress on the front end, AJAX can be utilized.
Here's a simplified AJAX implementation:
function updateProgressBar() { // Make an AJAX call to the PHP script $.ajax({ url: "upload_status.php", success: function(data) { // Update the progress bar with the returned value $("#progress").val(data); } }); }
This function periodically polls the PHP script to retrieve the current progress and updates the progress bar accordingly.
In the PHP script, upload_status.php, you can get the progress value using the $executing_class->get_progress() method and return it as a JSON response:
<?php header('Content-Type: application/json'); echo json_encode(['progress' => $executing_class->get_progress()]);
By invoking updateProgressBar() periodically using a timer, you can continuously display the progress to the user.
The above is the detailed content of How can AJAX be used to display real-time progress for file uploads?. For more information, please follow other related articles on the PHP Chinese website!