How can AJAX be utilized in PHP to send data from JavaScript to PHP without page refresh?

To send data from JavaScript to PHP without a page refresh, AJAX can be utilized. This allows for asynchronous communication between the client-side JavaScript and server-side PHP script. By making an AJAX request from JavaScript to a PHP script, data can be sent to the server and processed without reloading the entire page.

<?php
// PHP script to receive data from JavaScript using AJAX

// Check if data has been sent via POST method
if(isset($_POST['data'])){
    // Retrieve the data sent from JavaScript
    $data = $_POST['data'];
    
    // Process the data (e.g. save to database, perform calculations)
    
    // Send a response back to JavaScript
    echo "Data received: " . $data;
} else {
    echo "No data received";
}
?>