What are the best practices for implementing a loading bar or indicator in PHP to keep users engaged while data is being fetched?

To keep users engaged while data is being fetched in PHP, it is recommended to implement a loading bar or indicator. This can be achieved by using JavaScript along with PHP to show a loading animation while the data is being fetched in the background. By providing visual feedback to the user, it helps improve the user experience and reduces the perception of wait time.

<!-- HTML code to display a loading bar -->
<div id="loading-bar" style="display: none;">
    <div id="loading-bar-fill"></div>
</div>

<!-- JavaScript code to show the loading bar while data is being fetched -->
<script>
    document.getElementById('loading-bar').style.display = 'block';
    // Make an AJAX request to fetch data
    // Once data is fetched, hide the loading bar
    document.getElementById('loading-bar').style.display = 'none';
</script>