How to Create Simple Contact Form using Ajax, jQuery, Php and Mysql

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.

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.

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.

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.

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).

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.

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.

 

Author: Ahsan Zameer

I am a web developer and love to search new stuff on web. Trying different approaches and ideas to make web developing more interesting and enjoyable.