Contact Form using JQuery, PHP and MySql – updated

New Updates:

1. In order to make the contact form a little bit more secure, I have implemented an Secureimage PHP Captcha, more here: http://www.phpcaptcha.org
2. Again for security purposes in PHP logic there are extra checks to validate the email address.
3. Small bug fixing when returning the ajax response (if it failed or not).

Found an issue? Leave it in the comment and I will pick it up see how can I help you with. Have a question again you can leave a comment :)

I’ve decide to make this tutorial because when I was working for a project I couldn’t find a good contact form using css3, html, php, jquery and finaly mysql (this it will be optional). There are a lot of tutorials many are grate but something is missing. Hope that mine has what were you looking for.

At the end of this tutorial we will have a ajax form. Let’s stop talking and do the work.

1st Step HTML Form

 
<form id="contactForm" class="dl_form" method="post">
   <dl><dt>First Name</dt><dd>
     <input id="first_name" name="first_name" type="text" /></dd>
   </dl>
   <dl><dt>Last Name</dt><dd>
      <input id="last_name" name="last_name" type="text" /></dd>
   </dl>
   <dl><dt>Email</dt><dd>
       <input id="email" name="email" type="text" /></dd>
   </dl>
   <dl><dt>Phone</dt><dd>
       <input id="phone" name="phone" type="text" /></dd>
   </dl>
   <dl><dt>Subject:</dt><dd>
       <input id="subject" name="subject" type="text" /></dd>
   </dl>
   <dl><dt>Comment</dt><dd>
      <textarea id="message" style="width: 300px; height: 150px;" name="message"></textarea></dd>
    </dl>
    <dl><dt></dt><dd><input type="submit" value="submit" /></dd></dl>
</form>

What we did here is creating the form using HTML and some inline CSS. I did it with dl, dt html tags. I find them very useful. If you want to change it there’s no problem. So now that we created the form we are not done we have to create the thank you message and the error message. 2nd Step

Message sent succesefully!

You haven’t completed all required fileds!

With the help of CSS this two messages are going to be hidden.

Now that we have the HTML we can move forward and implement the CSS.

3th Step the CSS:

.dl_form  { }
.dl_form dl {
  clear:both;
  margin-bottom:7px;
  border-bottom:1px dashed #ccc;
  padding-bottom:7px;
}
.dl_form dl dt {
  float:left;
  margin-top:2px;
}
.dl_form dl dd {
  margin-left:120px;
}
.dl_form input[type="submit"] {
   background-color:#0186b3;
   border:1px solid #7c7c7c;
   padding:3px 15px;
   color:#fff;
   cursor:pointer;
   font-family:Helvetica, sans-serif;
   font-size:14px;
}
.dl_form input[type="text"] {
    background-color:#edfaff;
    border:1px solid #7c7c7c;
    padding:5px 2px;
    color:#404040;
    opacity:0.7;
}
.dl_form textarea:hover,
.dl_form textarea:focus,
.dl_form input[type="text"]:focus,
.dl_form input[type="text"]:hover {
   background-color:#e2f1f6;
}
.dl_form textarea  {
   background-color:#edfaff;
   border:1px solid #7c7c7c;
   height:70px;
   padding:2px;
   width:250px;
   color:#404040;
}
#note,
#error {
   display:none;
}
#error  {
   height:20px;
   background:red;
   position:absolute;
   top:40px;
   right:0;
   color:#fff;
   padding:5px 10px;
   font-size:16px;
}

Here we tell the dt tag to float left so the dd tag can come right after the dt to don’t go on a new line.

And created the style for the error message, thank you message and we styled the input tags including the textarea so they can look better.

4th Step JQuery

$(function(){
    //CONTACT FORM AJAX SUBMIT
    $('#contactForm').submit(function(){
          $.ajax({
	    url:'mailer.php',
	    type : 'POST',
	    dataType: 'json',
	    data: $(this).serialize(),
	       success: function(data){
		 if(data.error){
		    $('#error').css('display','block');
		}else {
		    $('#note').show();
		    $('#error').hide();
		    $("#fields").hide();
		}
	}
   })
   return false;
 })
})

Now let’s brake down this code.

$(function(){
    $('#contactForm').submit(function(){});
})

On document ready we tell to take the form with the id contactForm. And when this form is submitted do the rest of the code.

$.ajax({
  url:'mailer.php',
  type : 'POST',
  dataType: 'json',
  data: $(this).serialize(),
   success: function(data){
	if(data.error){
	  $('#error').css('display','block');
	}else {
	  $('#note').show();
	  $('#error').hide();
	  $("#fields").hide();
  }
}
})

Here we used the $.ajax function from jquery. The url is the path to the php file that will validate send and insert into database the information. “Type” we can send it through “GET” method or “POST” method. I choose the “POST” method that I did specified on the form action. DataType we used json.

data: $(this).serialize(),

“Data” takes all that data from inputs. And with the function serialize creates a text string in standard URL-encoded notation.

Forward on:

success: function(data){
  if(data.error){
     $('#error').css('display','block');
  }else {
    $('#note').show();
    $('#error').hide();
    $("#fields").hide();
  }
}

In this part of code if the form was send successfully then go forward. “data.error” is returned form mailer.php and if it has errors the error message will display else the thank you message will show and the error message and the form will hide.

5th Step

The php code from mailer.php

include_once 'securimage/securimage.php';
$securimage = new Securimage();
 
##############################################################################################################
    //database credentials
    $server     = 'localhost';
    $username   = 'root';
    $password   = '';
    $database   = 'yourDatabase';
    $connect    = mysqli_connect($server, $username, $password ) or die(mysqli_connect_error.'error connecting to db');
 
    //select database
    mysqli_select_db($database, $connect) or die(mysqli_error.'error selecting db');
 
    if(!empty($_POST)){
        $first_name = $_POST['first_name'];
        $last_name  = $_POST['last_name'];
        $email      = $_POST['email'];
        $phone      = $_POST['phone'];
        $subject    = $_POST['subject'];
        $message    = $_POST['message'];
        $captcha    = $_POST['captcha_code'];
        $filtered_email = filter_var($email, FILTER_VALIDATE_EMAIL);
 
        if(!empty($first_name) &amp;&amp; !empty($last_name) &amp;&amp; !empty($email) &amp;&amp; !empty($subject) &amp;&amp; !empty($message) &amp;&amp; !empty($captcha) )
        {
            //insert the data into DB
            mysqli_query("INSERT into yourTable (id, first_name, last_name, email, phone, subject, message )
                    VALUES ('', '".$first_name."', '".$last_name."',
                   '".$email."', '".$phone."', '".$subject."',
                   '".$message."' )") or die(mysqli_error);
 
            //prepare email headers
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=isoo-8859-1\r\n";
            $headers .= "From: ".$email."\r\n";
            $to = $email; //the email address you entered in the input filed on test page
 
            $subject = 'Contact Form';
            $body    = 'From: First Name: '.$first_name.' Last Name: '.$last_name.' 
                        E-mail: '.$email.' Phone: '.$phone.'  Subject: '.$subject.' Message: '.$message;
 
             //before sending the email make sure that the email address is correct
            if ( $filtered_email == false ) {
                echo json_encode(array(
                    'error' =&gt; true,
                    'msg'   =&gt; "The email address entered it's not correct!"
                ));
                exit;
            }
            //make sure that the captcha is valid
            if ( $securimage-&gt;check($captcha) == false ) {
                echo json_encode(array(
                    'error' =&gt; true,
                    'msg'   =&gt; "The security code entered was incorrect."
                ));
                exit;
            }
 
            $mail  = mail($to, $subject, $body, $headers);
 
            //check if email was sent
            if ( $mail ) {
                //finally send the ajax response
                echo json_encode(array(
                    'error' =&gt; false
                ));
                exit;
 
            } else {
                //finally send the ajax response
                echo json_encode(array(
                    'error' =&gt; true,
                    'msg'   =&gt; "Opss...Something went wrong. Message was not sent!"
                ));
                exit;
            }
 
        } else {
            echo json_encode(array(
                'error' =&gt; true,
                'msg'   =&gt; "You haven't completed all required fields!"
            ));
            exit;
       }
    }

Now let’s what this part does. First we connect to the database username, password, database.

Then we verify if the post was empty and we create variables so it can be easier for us to fallow when we insert into database and when we validate the from using PHP.

if(!empty($_POST)){
   $first_name = $_POST['first_name'];
   $last_name  = $_POST['last_name'];
   $email      = $_POST['email'];
   $phone      = $_POST['phone'];
   $subject    = $_POST['subject'];
   $message    = $_POST['message'];
   $captcha    = $_POST['captcha_code'];
   $filtered_email = filter_var($email, FILTER_VALIDATE_EMAIL);
}

Then we start to check if the inputs were empty. If they are not empty then we can go on.

if ( $mail ) {
   echo json_encode(array(
     'error' =&gt; false,
   ));
   exit;
}

This part of code we use the json_encode() function this will return string. And using the array we get all the values from the inputs and if there is no error we tell the json to return the error false. Then we can insert the datas received from the POST into database. We used the mysql_query() function so we can insert into database. Then we created the email template using the variables that received the values from our form.

}else{
   echo json_encode(array(
      'error' =&gt; true,
      'msg'  =&gt; "You haven't completed all required fileds!"
   ));
   exit;
}

If the form is empty then we go into the else condition. Here the json returns true and shows us the error message and returns us with the error message.

I hope you enjoyed my tutorial.

P.S. if you enter a real email address in the demo page. You will get an email from the contact form.

You can see here the example.

13 thoughts on “Contact Form using JQuery, PHP and MySql – updated

  1. Thanks for the tutorial!
    It is great and the form on the example works great, but the files on the .zip files are not the same as the example (no captcha, etc.).
    Is it possible to upload the new files?

    Thank you again!

    Elias

  2. I really enjoyed this quick tutorial, especially with captcha and added security. I was wondering if there was a way to move success or failure message to the the submit page instead of a separate page that just echos out message?
    Thanks!

    • It is quite easy to do. The form once submitted does an AJAX call to the mailer.php page. You can change that file and place your own custom HTML to contain a proper thank you message.

      In the example above the mailer returns a thank you message which just informs you that the form was submitted correctly with no extra HTML on it (for performances purposes we keep’t it simple)

    • Hi Ivona,
      We are looking into adding reCaptcha 2 including for responsive sites. Keep an eye on the updated version :)

  3. Hi,
    You have written a well piece but your code is deprecated now since it is using mysql_ to connect with database and is open for sql injections. You should update your code.

    • Hi Ahmed,

      Yes indeed, thank you for pointing it out :)
      Now is updated to mysqli, maybe in the future will be updated to mysql pdo.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.