What are the best practices for implementing AJAX requests to load specific content on a webpage with PHP?

When implementing AJAX requests to load specific content on a webpage with PHP, it is important to ensure that the server-side script responds with the appropriate data in a format that can be easily consumed by the client-side JavaScript. One common approach is to have a PHP script that fetches the required data from a database or external API and returns it in JSON format. This allows the client-side JavaScript to easily parse the data and update the webpage without requiring a full page reload.

<?php
// Assuming this is your server-side PHP script that handles the AJAX request

// Check if the request is an AJAX request
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
  
    // Fetch data from database or external API
    $data = array('content' => 'This is the specific content to be loaded');

    // Return data in JSON format
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}
?>