Create an AJAX Contact Form
A common feature of many websites is a contact form. Standard contact forms work just fine, but you can make them nicer by using AJAX to submit the form data in the background.
In this blog post, you’re going to learn how to create a website contact form that submits the form data using AJAX. We’ll be using jQuery to help simplify the JavaScript code and a simple PHP mailer script to handle sending the form data via email.
This form is not just limited to contact form you can use it for database manipulations or to submit any form via Ajax (without page reloading).
use this form
You can use this form as your contact form on your website. You can use this form to fetch data asynchronously, or even to perform database manipulation like insert/ update/ delete records.
3 simple steps to create the form
a.Building the HTML Form
b.Validate the form with jquery
c.Submitting the Form Using AJAX
Building the html form
Your first task is to set up the HTML form that will collect data from the user.Give your form field ID and setup a container for displaying error/success messages.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<form method="post" action="" name="contact_form" id="contact_form" > <div class="row"> <div class="label"><span style="color:#F00;">*</span>Name: </div> <div class="input-row" ><input name="your_name" id="your_name" type="text" class="textbox" autocomplete="off"><span id="your_nameErr" class="error" ></span></div> </div> <div class="row"> <div class="label"><span style="color:#F00;">*</span>Email: </div> <div class="input-row" ><input name="your_email" id="your_email" type="text" class="textbox" autocomplete="off"><span id="your_emailErr" class="error" ></span></div> </div> <div class="row"> <div class="label"></div> <div class="dummy-container" ><input type="submit" name="sub" value="Send" > <span class="loading"></span> </div> </div> <!--Form final confirmation of form submission--> <div class="output"></div> </form> |
rong>err appended to it. Add a div with output class that will hold the notification for final form submission.
Styling your form with css
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 |
.loginbox{margin:0 auto;width:480px;padding:30px;border:1px solid #EB028F; height:auto;} .row{ width:480px; height:auto; overflow:hidden; margin-bottom:10px; } .label{ width:100px;color:#000; float:left;padding-top:5px;} .input-row{ width:320px; height:32px; background-color:#FFF; float:left; position:relative; } .input-textarea-row{ width:320px; height:65px; background-color:#FFF; float:left; position:relative; } .dummy-container{ width:317px; height:32px; background:none; color:#000; float:left; padding:0px;position:relative;} .textbox{ width:100%; height:24px; border:1px solid #63F;outline:none; background:transparent; color:#000; padding:0px; } .textarea{ width:100%; height:57px; border:1px solid #63F; outline:none; background:transparent; color:#000; padding:0px; } .error { background: none repeat scroll 0 0 #FFFFFF; border: 1px solid #F00; font-size: 11px; width: 314px; top:0%; left:0%; height:20px; padding:2px; position:absolute; display:none; } .loading{ background:url(ajax-loader.gif) no-repeat; width:32px; height:16px; position:absolute; margin-left:10px; margin-top:3px; visibility:hidden; } .output{ margin:5px; widows:480px; padding:5px; display:none;} .success{border:2px solid #0066FF;} .failed{border:2px solid #FF0000;} |
Validate the form with jQuery
I have used jQuery to validate the form. If there is an error on data validation, alert will be displayed above its relevant field.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script type="text/javascript"> $(document).ready(function() { $("#contact_form").submit(function() { $('.error').fadeOut(200); $('.output').removeClass("success failed"); $('.output').css("display", "none"); // vlidate form here if(validateForm()) { sendForm(); } return false; }); }); </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function validateForm() { var errCnt = 0; var your_name = $.trim( $("#your_name").val()); // validate name if (your_name == "" ) { $("#your_nameErr").html("Enter your name."); $('#your_nameErr').fadeIn("fast"); errCnt++; } else if (your_name.length < 3 ) { $("#your_nameErr").html("Enter atleast 2 letter."); $('#your_nameErr').fadeIn("fast"); errCnt++; } if(errCnt > 0) return false; else return true; } |
Submitting the Form Using AJAX
Once the data is validated ( returns true) an ajax call is requested to the server, which returns error/success message in a json format. The result (json) is parsed and the message is notified to the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function sendForm() { $.ajax({ type: "POST", url: "process.php", data: $("#contact_form").serialize(), cache: false, beforeSend: function() { $(".loading").css("visibility", "visible"); }, success: function(html) { $(".loading").css("visibility", "hidden"); var obj = $.parseJSON(html); $(".output").html( obj.msg ); $(".output").addClass( obj.msgtype ); $(".output").slideDown("slow"); $('#contact_form').trigger("reset"); } }); } |
PHP page to process the form and return confirmation message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php function clean($str) { return addslashes(trim($str)); } $name = clean($_REQUEST["your_name"]); $your_email = clean($_REQUEST["your_email"]); $subject = clean($_REQUEST["your_subject"]); $comments = clean($_REQUEST["your_comments"]); $sex = clean($_REQUEST["your_sex"]); $game = clean($_REQUEST["your_fav_game"]); // now you can use the files to process form // do whatever you need to do here if (true) { echo json_encode( array("msg" => "Form Submitted Successfully", "msgtype" => "success")); } else { echo json_encode( array("msg" => "Error Processing form. Please try later", "msgtype" => "failed")); } ?> |