How can AJAX be implemented to send data from JavaScript to a PHP script on the server?

To send data from JavaScript to a PHP script on the server using AJAX, you can use the XMLHttpRequest object in JavaScript to make an asynchronous request to the PHP script. The PHP script can then receive the data sent from the JavaScript and process it accordingly.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $data = json_decode(file_get_contents("php://input"), true);
    // Process the data received from JavaScript
    // For example, you can access the data using $data['key']
    // and perform any necessary operations
    // Send a response back to JavaScript if needed
    echo json_encode(["message" => "Data received successfully"]);
}
?>