In this article, we will learn to contact us form with JQuery validation and also will send mail to the user on the successful submission form


Example

will make contact us form in HTML and add bootstrap, jQuery and jquery form validation plugin in server-side we will use PHP for submitting form data and send mail after successful submission



Project structure

before writing code let me show you my project structure.

php-tutorial/
contacts_list.sql
┣ data.php
┣ db_config.php
┗ index.php


Database structure

use the following code to create a contact list table in your database


-- phpMyAdmin SQL Dump
-- version 4.9.5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jan 27, 2021 at 05:52 PM
-- Server version: 8.0.22
-- PHP Version: 7.3.6

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `rathorji_demo`
--

-- --------------------------------------------------------

--
-- Table structure for table `contacts_list`
--

CREATE TABLE `contacts_list` (
  `id` int NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `mobile_no` varchar(50) NOT NULL,
  `Message` text NOT NULL,
  `sent_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `contacts_list`
--

INSERT INTO `contacts_list` (`id`, `name`, `email`, `mobile_no`, `Message`, `sent_date`) VALUES
(1, 'Gajanand', 'gajanand.kgn@gmail.com', '8827213789', 'test messages', '2021-01-27 17:50:31');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `contacts_list`
--
ALTER TABLE `contacts_list`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `contacts_list`
--
ALTER TABLE `contacts_list`
  MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


db_config.php

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = "";/* Password */
$dbname = "php-tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}


index.php

<?php session_start(); ?>
<!DOCTYPE html>
<html>
    <head>
        <title>PHP Contact Form Tutorial with JQuery Validation</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous" />
        <style type="text/css">
            
            body{
                background: #ccc;
            }
            
            .my-formcontainer{
                width: 800px;
                background: #fff;
                padding: 20px;
                margin: 20px auto;
            }
            
            .error {
                color: #DC143C;
                font-weight: 400;
                display: block;
                padding: 6px 0 0;
                font-size: 14px;
                margin-bottom: 0px !important;
            }
            .form-control.error {
                border-color: #DC143C;
                padding: .375rem .75rem;
            }
        </style>
    </head>
    <body>


        <div class="my-formcontainer">

            <h3>Contact us</h3>
            
            <?php if (!empty($_SESSION['message'])) { ?>
                <div class="alert text-center alert-success" role="alert">
                    <?php
                    echo $_SESSION['message'];
                    unset($_SESSION['message']);
                    ?>
                </div>
            <?php } ?>

            <form action="data.php" name="contact-form" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name" id="name">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" name="email" id="email">
                </div>
                <div class="form-group">
                    <label>Mobile No.</label>
                    <input type="text" class="form-control" name="mobile_no" id="mobile_no">
                </div>
                <div class="form-group">
                    <label>Message</label>
                    <textarea class="form-control" name="message" id="message" rows="4"></textarea>
                </div>
                <div class="form-group">
                    <button class="btn btn-success btn-lg">Submit</button>
                </div>
            </form>

        </div>


        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        
        
        <!-- https://jqueryvalidation.org/-->
        <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.min.js"></script>
        <script>
            $(function() {
                $("form[name='contact-form']").validate({
                    // Define validation rules
                    rules: {
                        name: "required",
                        email: "required",
                        mobile_no: "required",
                        subject: "required",
                        message: "required",
                        name: {
                            required: true
                        },
                        email: {
                            required: true,
                            email: true
                        },
                        mobile_no: {
                            required: true,
                            minlength: 10,
                            maxlength: 10,
                            number: true
                        },
                        subject: {
                            required: true
                        },
                        message: {
                            required: true
                        }
                    },
                    // Specify validation error messages
                    messages: {
                        name: "The name field is required.",
                        email: {
                            required: "The email field is required",
                            minlength: "Please enter a valid email address"
                        },
                        mobile_no: {
                            required: "The mobile number field is required",
                            minlength: "Mobile number must be min 10 characters long",
                            maxlength: "Mobile number must not be more than 10 characters long"
                        },
                        subject: "The subject field is required",
                        message: "The message field is required"
                    },
                    submitHandler: function(form) {
                        form.submit();
                    }
                });
            });
        </script>
    </body>
</html>


data.php

<?php

session_start();
include 'db_config.php';
extract($_POST);
// Send email
if (!empty($_POST)) {
    $to = "gajanand.kgn@gmail.com";
    $subject = 'Contact';
    $header = "From: " . $name . "<" . $email . ">\r\n";

    mail($to, $subject, $message, $header);

    // Store contactor data in database
    $q = "INSERT INTO contacts_list(name, email, mobile_no, message, sent_date)
            VALUES ('{$name}', '{$email}', '{$mobile_no}', '{$message}', now())";

    $sql = mysqli_query($con, $q);

    if (!$sql) {
        die("MySQL query failed.");
    } else {
        $_SESSION['message'] = "Message Sent Successfully";
    }
} else {
    $_SESSION['message'] = "Message coudn't be sent, try again";
}

header("Location:index.php");


Output:




Once you have submitted data, it will show a success message like this: