Are there any best practices for optimizing the performance of data retrieval using buttons in PHP?

When retrieving data using buttons in PHP, it is important to optimize the performance by minimizing unnecessary database queries and ensuring efficient code execution. One best practice is to use AJAX to fetch data asynchronously without reloading the entire page, reducing server load and improving user experience.

// Example of using AJAX to retrieve data on button click

// HTML button element
<button id="fetchDataBtn">Fetch Data</button>

// JavaScript code to handle button click event and make AJAX request
<script>
document.getElementById('fetchDataBtn').addEventListener('click', function() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'fetch_data.php', true);
  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 400) {
      // Data retrieved successfully, update UI with response
      console.log(xhr.responseText);
    } else {
      // Handle error
      console.error('Error fetching data');
    }
  };
  xhr.send();
});
</script>

// PHP code in fetch_data.php to retrieve data from database
<?php
// Connect to database
$conn = new mysqli('localhost', 'username', 'password', 'database');

// Query to fetch data
$query = "SELECT * FROM table_name";
$result = $conn->query($query);

// Fetch data as associative array
$data = $result->fetch_all(MYSQLI_ASSOC);

// Return data as JSON
echo json_encode($data);

// Close database connection
$conn->close();
?>