How can AJAX requests be used to validate form input before submission in PHP?

When validating form input before submission in PHP, AJAX requests can be used to send the form data to a PHP script that performs the validation. The PHP script can then return a response indicating whether the input is valid or not. This allows for real-time validation without requiring the user to submit the form.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Perform form validation here
    $input = $_POST['input'];
    
    // Validate input (example validation)
    if (empty($input)) {
        echo "Input cannot be empty";
    } else {
        echo "Input is valid";
    }
}
?>