How can AJAX requests be utilized in PHP to provide feedback to the browser during a long-running loop?
When running a long-running loop in PHP, the browser may not receive any feedback until the loop has completed, which can lead to a poor user experience. To provide feedback during the loop, AJAX requests can be utilized to periodically send updates to the browser. This allows the browser to display progress to the user in real-time.
<?php
// Simulate a long-running loop
for ($i = 1; $i <= 10; $i++) {
// Perform some processing
sleep(1);
// Send progress update to the browser
echo json_encode(['progress' => $i * 10]) . "\n";
// Flush the output buffer to send the update immediately
ob_flush();
flush();
}
?>