How can AJAX be utilized in PHP to automatically refresh and update content on a webpage, such as rotating images?

To automatically refresh and update content on a webpage, such as rotating images, AJAX can be utilized in PHP. By using AJAX, we can make asynchronous requests to the server to fetch new images or data without reloading the entire page. This allows for a seamless and dynamic user experience.

<?php
// PHP code to fetch and rotate images using AJAX

// Fetch images from a directory
$images = glob('images/*.jpg');

// Randomly select an image to display
$randomImage = $images[array_rand($images)];

// Output the image tag
echo '<img src="' . $randomImage . '" alt="Rotating Image">';

// JavaScript code for AJAX request
?>
<script>
    setInterval(function() {
        // AJAX request to fetch a new image
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'get_new_image.php', true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Update the image source with the new image
                document.querySelector('img').src = xhr.responseText;
            }
        };
        xhr.send();
    }, 5000); // Refresh every 5 seconds
</script>