Show AJAX upload status on progress element
Handling long-running file uploads in PHP often requires more than just a standard POST request. When a script takes ten seconds or longer to process a file, users need visual feedback to avoid assuming the browser has frozen. The HTML5 <progress> element is the modern tool for this job, but updating it dynamically from a server-side class that isn't part of your frontend state requires a specific architectural approach.
The core challenge you are facing is not about creating new objects, but rather about decoupling the progress calculation on the server from the DOM manipulation on the client. In your executing class, you have a $progress property and a get_progress() method. This separation is standard in object-oriented design, but it creates a communication gap: the PHP script calculates the value, while the JavaScript needs to display it. To bridge this, you must treat the progress update as a distinct event rather than part of the initial request payload.
The most robust solution involves leveraging setInterval or setTimeout on the client side to poll for updates, or utilizing Server-Sent Events (SSE) if your PHP environment supports them. Given your current setup with a returning PHP class, polling is the most compatible path forward without requiring complex WebSocket infrastructure. You will need to establish a long-lived connection that allows the server to push small JSON payloads containing the updated progress percentage at regular intervals.
Here is how you can structure this on the frontend using jQuery and vanilla JavaScript. First, ensure your <progress> element exists in the DOM and has an associated ID:
<div id="upload-container">
<input type="file" id="fileInput" />
<progress id="progressBar" value="0" max="100"></progress>
<span id="statusText">Uploading...</span>
</div>
On the client side, you intercept the file upload and initiate an AJAX request to your PHP endpoint. Crucially, this request must be asynchronous and capable of receiving partial responses. Your PHP script should output a JSON object with the current progress value every time get_progress() is called within the loop:
{ "progress": 45 }
Your JavaScript logic needs to listen for these updates. A common pattern is to use setInterval to poll the server, though this consumes more bandwidth than a push-based model. Alternatively, you can configure your PHP script to echo the progress data and close the connection (ob_end_flush()) after each update, allowing the browser to process the stream immediately.
$('#fileInput').on('change', function(e) {
var file = e.target.files[0];
var progressBar = $('#progressBar');
$.ajax({
url: '/upload-endpoint',
type: 'POST',
data: { file: file },
xhrFields: {
// Enable chunked uploads if supported by your PHP handler
uploadProgress: function(event, loaded, total) {
var percentComplete = Math.round(loaded / total * 100);
progressBar.attr('value', percentComplete);
progressBar.attr('max', file.size);
}
},
success: function(response) {
// Handle final completion or server-side progress updates
}
});
});
However, relying solely on xhrFields.uploadProgress only gives you the transfer speed, not the processing status calculated by your PHP class. To display the specific value from $progress, your PHP script must echo a JSON fragment after calculating the percentage and then flush the buffer. Your JavaScript listener should parse this JSON and update the value attribute of the <progress> tag immediately upon receipt.
This approach ensures that the user sees real-time feedback without needing to wait for the entire upload to complete before seeing movement. The trade-off is increased network overhead if you poll too frequently, so tuning the interval or switching to a stream-based echo in PHP is essential for performance. If you are building this within a Laravel application, consider using Laravel's built-in event broadcasting or Livewire to manage these state updates more elegantly, but the fundamental principle remains: decouple the calculation from the display by sending discrete messages over the HTTP connection.