How can AJAX requests be utilized in PHP to improve pagination and loading times for websites with external data sources?

When dealing with websites that rely on external data sources for pagination, loading times can be slow due to the need to fetch and process large amounts of data. Utilizing AJAX requests in PHP can help improve pagination and loading times by fetching and displaying data asynchronously, without requiring a full page reload.

// PHP code snippet utilizing AJAX requests for pagination

// Check if AJAX request is being made
if(isset($_GET['page']) && isset($_GET['limit'])) {
    $page = $_GET['page'];
    $limit = $_GET['limit'];
    
    // Fetch data from external source based on pagination parameters
    $data = fetchDataFromExternalSource($page, $limit);
    
    // Process and display data
    foreach($data as $item) {
        echo '<div>' . $item['title'] . '</div>';
    }
    
    // Additional pagination logic can be added here
}

// Function to fetch data from external source
function fetchDataFromExternalSource($page, $limit) {
    // Code to fetch data from external source based on pagination parameters
    // Return data as an array
}