What are some best practices for handling PHP functions within HTML elements like buttons for exporting data?

When handling PHP functions within HTML elements like buttons for exporting data, it is important to separate the PHP code from the HTML code to maintain clean and organized code structure. One way to achieve this is by using AJAX to call a PHP script when the button is clicked, which can then handle the data export functionality. This approach keeps the presentation layer (HTML) separate from the business logic layer (PHP), making the code easier to maintain and debug.

<!-- HTML code for the button -->
<button id="exportButton">Export Data</button>

<!-- JavaScript code to handle button click and AJAX call -->
<script>
document.getElementById('exportButton').addEventListener('click', function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'export_data.php', true);
    xhr.send();
});
</script>

<!-- PHP code in export_data.php to handle data export -->
<?php
// Perform data export functionality here