How can PHP be used to update a file without refreshing the page?

To update a file without refreshing the page using PHP, you can make an AJAX request to a PHP script that handles the file update operation. This PHP script can receive data from the client-side, update the file, and return a response back to the client. By using AJAX, the page can update dynamically without requiring a full page refresh.

<?php
// Check if the data is received through POST request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the data sent from the client-side
    $data = $_POST['data'];
    
    // Update the file with the received data
    $file = fopen("example.txt", "w");
    fwrite($file, $data);
    fclose($file);
    
    // Return a response back to the client
    echo "File updated successfully!";
}
?>