How can JavaScript be used to complement PHP functionality in a web application?

JavaScript can be used to complement PHP functionality in a web application by allowing for dynamic content updates without needing to reload the entire page. This can enhance user experience by providing real-time interactions and reducing server load. By using AJAX requests, JavaScript can communicate with the server to fetch or send data asynchronously, making the application more responsive and interactive.

<?php
// PHP code to handle AJAX request
if(isset($_POST['data'])){
    $data = $_POST['data'];
    
    // Process the data
    
    // Return response
    echo json_encode(['message' => 'Data processed successfully']);
}
?>