Home > Backend Development > PHP Tutorial > How can AJAX be used to display real-time progress for file uploads?

How can AJAX be used to display real-time progress for file uploads?

Mary-Kate Olsen
Release: 2024-11-11 15:46:02
Original
187 people have browsed it

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);
    }
  });
}
Copy after login

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()]);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template