What are the advantages of using AJAX for data retrieval in PHP instead of embedding data directly in the HTML document?

When embedding data directly in the HTML document, the page size increases, leading to slower load times and increased bandwidth usage. Using AJAX for data retrieval allows for asynchronous loading of data, resulting in faster and more efficient page rendering. Additionally, AJAX enables dynamic content updates without requiring a full page reload.

<?php
// AJAX data retrieval in PHP
if(isset($_GET['data'])){
    // Retrieve data from database or external API
    $data = fetchData($_GET['data']);
    
    // Return data as JSON response
    echo json_encode($data);
}

function fetchData($data){
    // Implement data retrieval logic here
    return $data;
}
?>