What are some best practices for displaying "Please Wait" messages in PHP scripts during lengthy processing tasks?

When processing tasks in PHP scripts that take a long time to complete, it is essential to display a "Please Wait" message to inform users that the operation is ongoing. This helps manage user expectations and prevents them from thinking the script has frozen. One common approach is to use AJAX to asynchronously update a loading message on the frontend while the PHP script is running in the background.

// Display "Please Wait" message using AJAX in PHP script

// PHP script that initiates the lengthy processing task
// For demonstration purposes, let's assume the task takes 5 seconds to complete
sleep(5);

// AJAX response to update the loading message on the frontend
echo json_encode(['message' => 'Please wait, processing task...']);