What are the best practices for including external PHP files in JavaScript code?

When including external PHP files in JavaScript code, it is important to use AJAX to make a request to the PHP file and retrieve the data. This allows for dynamic loading of PHP content without needing to reload the entire page. Additionally, make sure to properly sanitize and validate any user input to prevent security vulnerabilities.

// PHP file (example.php)
<?php
// Your PHP code here
echo "Hello from PHP!";
?>

// JavaScript code
<script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'example.php', true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      console.log(xhr.responseText);
    }
  };
  xhr.send();
</script>