How can AJAX requests be properly implemented in PHP scripts?

To properly implement AJAX requests in PHP scripts, you need to handle the incoming request, process the data, and send back a response in a format like JSON. This can be done by checking if the request is an AJAX request, parsing the data sent in the request, performing any necessary processing, and then returning a response in the desired format.

<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Process AJAX request
    $data = $_POST['data']; // Assuming data is sent via POST
    $result = // Process the data here

    // Return response
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
} else {
    // Handle non-AJAX request
}
?>