How can PHP and JavaScript be used together to provide a more user-friendly experience for input validation?

When using PHP for input validation, it typically requires a form submission to check the input and provide feedback to the user. To create a more user-friendly experience, JavaScript can be used to perform client-side validation before the form is submitted. This allows for instant feedback to the user without needing to reload the page.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $input = $_POST["input"];
    
    // Server-side validation
    if (empty($input)) {
        echo "Please enter a value.";
    } else {
        // Process the input
        echo "Input successfully submitted.";
    }
}
?>

<form method="post" onsubmit="return validateForm()">
    <input type="text" name="input" id="input">
    <button type="submit">Submit</button>
</form>

<script>
function validateForm() {
    var input = document.getElementById("input").value;
    
    // Client-side validation
    if (input == "") {
        alert("Please enter a value.");
        return false;
    }
    
    return true;
}
</script>