Contact us form with jquery validation and mail send in php ajax

Contact us form with jquery validation and mail send in php ajax

Here's an example of a complete PHP code for sending a contact form email with jQuery validation on the client side. This example assumes you have jQuery included in your project. You can include it using a CDN or by downloading and hosting the jQuery file.

index.html

create index.html file and put this code in this  file and save in folder.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Us</title>
    <!-- Include jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>

<div class="container mt-5">
    <h2>Contact Us</h2>
    <form id="contact-form" method="post">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" class="form-control" id="name" name="name">
            <span class="error" id="error-name"></span>
        </div>

        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" class="form-control" id="email" name="email">
            <span class="error" id="error-email"></span>
        </div>

        <div class="form-group">
            <label for="subject">Subject:</label>
            <input type="text" class="form-control" id="subject" name="subject">
            <span class="error" id="error-subject"></span>
        </div>

        <div class="form-group">
            <label for="message">Message:</label>
            <textarea class="form-control" id="message" name="message"></textarea>
            <span class="error" id="error-message"></span>
        </div>

        <button type="button" class="btn btn-primary" id="submitBtn">Submit</button>
    </form>
</div>

<script>
    $(document).ready(function() {
        $("#submitBtn").click(function() {
            // Clear previous error messages
            $(".error").text("");

            // Validate form using jQuery
            var valid = true;

            // Name validation
            var name = $("#name").val();
            if (name === "") {
                $("#error-name").text("Name is required");
                valid = false;
            }

            // Email validation
            var email = $("#email").val();
            if (email === "") {
                $("#error-email").text("Email is required");
                valid = false;
            } else if (!isValidEmail(email)) {
                $("#error-email").text("Invalid email format");
                valid = false;
            }

            // Subject validation
            var subject = $("#subject").val();
            if (subject === "") {
                $("#error-subject").text("Subject is required");
                valid = false;
            }

            // Message validation
            var message = $("#message").val();
            if (message === "") {
                $("#error-message").text("Message is required");
                valid = false;
            }

            if (valid) {
                // If all fields are filled and valid, submit the form using AJAX
                $.ajax({
                    type: "POST",
                    url: "process_contact.php",
                    data: $("#contact-form").serialize(),
                    success: function(response) {
                        alert(response); // Display the server response
                        // You can also update the UI or redirect the user here
                    },
                    error: function() {
                        alert("Error sending the message");
                    }
                });
            }
        });
    });

    // Email validation function
    function isValidEmail(email) {
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }
</script>

</body>
</html>

process_contact.php:

create process_contact.php FIile

 

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Form validation
    $name = test_input($_POST["name"]);
    $email = test_input($_POST["email"]);
    $subject = test_input($_POST["subject"]);
    $message = test_input($_POST["message"]);

    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        echo "All fields are required.";
    } else {
        // Email receiver
        $to = "your_email@example.com";

        // Subject and message for the email
        $email_subject = "New Contact Form Submission: $subject";
        $email_message = "Name: $name\n";
        $email_message .= "Email: $email\n";
        $email_message .= "Subject: $subject\n";
        $email_message .= "Message:\n$message";

        // Additional headers
        $headers = "From: $email";

        // Send the email
        if (mail($to, $email_subject, $email_message, $headers)) {
            echo "Thank you for contacting us! We will get back to you soon.";
        } else {
            echo "Sorry, something went wrong and we couldn't send your message.";
        }
    }
}

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

Remember to replace "your_email@example.com" with the actual email address where you want to receive the contact form submissions. Customize the success and error handling in the jQuery section according to your requirements.




Mahendra Pratap Singh

Hey there! I'm a Senior Full Stack Developer with 10 +years of experience in the tech world. I've spent a lot of time working with different tools and languages, like PHP, WordPress, Laravel, and CodeIgniter... Read More >>

Leave a Comment