How can AJAX be utilized to improve user interaction with PHP-generated content?

Issue: When PHP generates content on a webpage, the user experience can sometimes be slow and clunky as the page needs to reload entirely to display new content. Utilizing AJAX can help improve user interaction by allowing for dynamic content updates without needing to refresh the entire page.

// PHP code to generate content dynamically and utilize AJAX for improved user interaction

<?php
// Generate some PHP content
echo "<div id='dynamic-content'>This is some dynamically generated content</div>";
?>

<script>
// AJAX request to fetch new content without refreshing the page
function fetchNewContent() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'new_content.php', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById('dynamic-content').innerHTML = xhr.responseText;
        }
    };
    xhr.send();
}

// Call fetchNewContent function to update content dynamically
fetchNewContent();
</script>