How can PHP and JS be used together to optimize a contact form on a website?

To optimize a contact form on a website using PHP and JS, you can use PHP to validate the form input on the server-side to ensure data integrity and security, and then use JS to provide real-time feedback to the user on the client-side without having to reload the page.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    $name = test_input($_POST["name"]);
    $email = test_input($_POST["email"]);
    $message = test_input($_POST["message"]);

    // Process form data
    // Your code here to handle the form submission
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>