Contact form is one of the common feature of every website to get user opinion. Almost 99.9% of websites need contact form to interact with user. So in this tutorial, I am going to create simple contact form using ajax, jquery, php and mysql.
Steps involved in Contact Form
- Write form HTML
- Write Css
- Add jQuery validation and jQuery Ajax
- Create Database table and Database connection file
- Get response in php file and save into Mysql Database
Step 1: Write form HTML
First step to write html in contact-form.php file. Most of the contact forms have Name, Email, Phone and Comment fields. Name and Email fields are mandatory fields. I will use ‘*’ in front of label for required fields.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<div class="form-wrapper"> <form name="contact-form" action="" method="post" id="contact-form"> <label>Name <span>*</span></label> <input type="text" name="your_name"> <label>Email <span>*</span></label> <input type="email" name="your_email"> <label>Phone </label> <input type="text" name="your_phone"> <label>Comment</label> <textarea name="comments" cols="28" rows="5"></textarea> <input type="submit" name="submit" value="Submit" id="submit_form"> <img src="img/loading.gif" id="loading-img"> </form> <div class="response_msg"></div> </div> |
In above code I write all my html code under ‘form-wrapper’. I also add image having id ‘loading-img’ just before form closing tag and after form I create a div name as ‘response_msg’.
Step 2: Write Css
Next step to add some style and colors to contact form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
body{ font-family:verdana; margin:0px; } .form-wrapper{ margin:10px; } .form-wrapper label{ display:block; font-size:14px; } .form-wrapper input[type=text], .form-wrapper input[type=email]{ margin-bottom:5px; width:180px; height:20px; border:1px solid #eeeeee; } .form-wrapper span{ color:#ee0000; } .form-wrapper input[type=submit]{ display:block; margin-top:5px; border:0px; background:#ee0000; color:#ffffff; height:30px; border-radius:5px; } .form-wrapper input[type=submit]:hover{ background:#ee0022; } .form-wrapper textarea{ border:1px solid #eeeeee; } #loading-img{ display:none; } .response_msg{ margin-top:10px; font-size:13px; background:#E5D669; color:#ffffff; width:250px; padding:3px; display:none; } |
In above CSS code, you may notice that #loading-img and .response_msg both have display:none css property. Because, right now I don’t want to display them. #loading-img will display when ajax will trigger and .response_msg will display the response from another file (file that get form data and save it into database).
Step 3: Add jQuery validation and jQuery Ajax
In this step, I am going to add jquery validation for required fields (name, email) and jquery ajax code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("#contact-form").on("submit",function(e){ e.preventDefault(); if($("#contact-form [name='your_name']").val() === '') { $("#contact-form [name='your_name']").css("border","1px solid red"); } else if ($("#contact-form [name='your_email']").val() === '') { $("#contact-form [name='your_email']").css("border","1px solid red"); } else { $("#loading-img").css("display","block"); var sendData = $( this ).serialize(); $.ajax({ type: "POST", url: "get_response.php", data: sendData, success: function(data){ $("#loading-img").css("display","none"); $(".response_msg").text(data); $(".response_msg").slideDown().fadeOut(3000); $("#contact-form").find("input[type=text], input[type=email], textarea").val(""); } }); } }); $("#contact-form input").blur(function(){ var checkValue = $(this).val(); if(checkValue != '') { $(this).css("border","1px solid #eeeeee"); } }); }); </script> |
First I prevent default submit behavior and then add validation for name and email in a if clause. If both name and email fields will not empty at the time of submitting form then loading image will display and then I get form data and send it to get_response.php file. I will receive response from get_response.php file and display that response into .response_msg div.
Step 4: Create Database table and Database connection file
Before adding form data into database I should create table in mysql database. So here is create table code.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
CREATE TABLE `contact_form_info` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(90) NULL DEFAULT NULL, `email` VARCHAR(90) NULL DEFAULT NULL, `phone` INT(14) NULL DEFAULT NULL, `comments` TEXT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=MyISAM AUTO_INCREMENT=18; |
I have created contact_form_info table. Column names are id, name, email, phone and comments. Now I have to create database connection file (config.php).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $host = "localhost"; $userName = "root"; $password = ""; $dbName = "my_website"; // Create database connection $conn = new mysqli($host, $userName, $password, $dbName); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?> |
Step 4: Get response in php file and save into Mysql Database
Once table and config.php file is created. Now its time to create get_response.php file in which I get data from contact-form.php and save it into database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php require_once("config.php"); if((isset($_POST['your_name'])&& $_POST['your_name'] !='') && (isset($_POST['your_email'])&& $_POST['your_email'] !='')) { $yourName = $_POST['your_name']; $yourEmail = $_POST['your_email']; $yourPhone = $_POST['your_phone']; $comments = $_POST['comments']; $sql="INSERT INTO contact_form_info (name, email, phone, comments) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."', '".$comments."')"; if(!$result = $conn->query($sql)){ die('There was an error running the query [' . $conn->error . ']'); } else { echo "Thank you! We will contact you soon"; } } else { echo "Please fill Name and Email"; } ?> |
First of all I have added config.php for database connection and then I checked if name and email field are empty or not. If both or any one of the field is empty I am sending “Please fill Name and Email”. Otherwise I get form data and save into database.