How can PHP be used to automatically populate input fields with the current date and time upon pressing a button?

To automatically populate input fields with the current date and time upon pressing a button in PHP, you can use JavaScript along with PHP to achieve this functionality. When the button is clicked, a JavaScript function can be triggered to set the current date and time in the input fields. This can be done by sending an AJAX request to a PHP script that generates the current date and time, and then returning it back to the JavaScript function to populate the input fields.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $currentDateTime = date('Y-m-d H:i:s');
    echo $currentDateTime;
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Populate Date and Time</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="text" id="datetime">
    <button id="populateBtn">Populate Date and Time</button>

    <script>
        $(document).ready(function() {
            $('#populateBtn').click(function() {
                $.ajax({
                    url: 'populate_datetime.php',
                    type: 'POST',
                    success: function(response) {
                        $('#datetime').val(response);
                    }
                });
            });
        });
    </script>
</body>
</html>