What are the differences between JavaScript and PHP when it comes to form validation, and how should they be integrated for optimal results?

When it comes to form validation, JavaScript is typically used for client-side validation to provide immediate feedback to users, while PHP is used for server-side validation to ensure data integrity. To integrate both for optimal results, you can use JavaScript to perform basic validation on the client side and then submit the form to PHP for further validation and processing.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    
    // Server-side validation
    if (empty($name) || empty($email)) {
        echo "Please fill out all fields.";
    } else {
        // Process form data
        echo "Form submitted successfully!";
    }
}
?>