How can PHP communicate with JavaScript to create a more interactive image display?

To create a more interactive image display, PHP can communicate with JavaScript by passing data between the two languages using AJAX. This allows PHP to dynamically update the image display based on user interactions without reloading the entire page.

<?php
// PHP code to retrieve image data
$imageData = array(
    'image1.jpg',
    'image2.jpg',
    'image3.jpg'
);

// Convert PHP array to JSON
$imageDataJSON = json_encode($imageData);
?>

<script>
// JavaScript code to handle AJAX request
var imageData = <?php echo $imageDataJSON; ?>;

// Function to update image display
function updateImageDisplay(imageIndex) {
    var imageSrc = imageData[imageIndex];
    document.getElementById('image-display').src = imageSrc;
}

// Example usage
updateImageDisplay(0);
</script>