How can a progress bar or a loading indicator be displayed while fetching data to be inserted into a specific div (id=content) using PHP and Ajax?

To display a progress bar or loading indicator while fetching data to be inserted into a specific div using PHP and Ajax, you can use JavaScript to show the loading indicator before making the Ajax request and hide it once the data has been successfully loaded into the div.

// PHP code to handle the Ajax request and fetch data
<?php
if(isset($_POST['getData'])) {
    // Fetch data from the server
    $data = fetchData(); // Function to fetch data
    
    // Return the data as JSON
    echo json_encode($data);
    exit;
}

function fetchData() {
    // Simulate fetching data
    sleep(2); // Simulate delay
    
    return "Data fetched successfully!";
}
?>

// JavaScript code to handle the Ajax request and display loading indicator
<script>
$(document).ready(function(){
    // Show loading indicator
    $('#loading').show();
    
    $.ajax({
        url: 'fetchData.php',
        type: 'POST',
        data: {getData: true},
        success: function(response) {
            // Hide loading indicator
            $('#loading').hide();
            
            // Insert data into div
            $('#content').html(response);
        },
        error: function() {
            // Hide loading indicator
            $('#loading').hide();
            
            // Display error message
            $('#content').html('Error fetching data');
        }
    });
});
</script>