A simple AJAX (Contact) Form with Validation (JQuery)

Save to StumbleUpon Stumble Upon it!   Save to Del.icio.us Save to Del.icio.us

Hello,

The aim of this tutorial is to help you to create a simple (tableless) contact form using AJAX, JQuery & PHP. We will have a HTML page which will contain the form, a CSS file, a php page where the data will be sent and another file where the validation function(s) will be located. JQuery is a new and powerful library which simplifies the way that you write JavaScript.

Step 1 - Creating the configuration file

config.php

<?php
// To
define("WEBMASTER_EMAIL", 'your_name@domain.com');
?>

Here you should fill the e-mail address where you wish to receive the mail as well as the address where you wish to receive the replies (usually the same).

Step 2 - Creating the css file

style.css

/*
Credits: Bit Repository
CSS Library: http://www.bitrepositiry.com/
*/

html, body  { padding: 0; border: 0px none; }

.notification_error
{
border: 1px solid #A25965;
height: auto;
width: 90%;
padding: 4px;
background: #F8F0F1;
text-align: left;
-moz-border-radius: 5px;
}

.notification_ok
{
border: 1px #567397 solid;
height: auto;
width: 90%
padding: 8px;
background: #f5f9fd;
text-align: center;
-moz-border-radius: 5px;
}

.info_fieldset { -moz-border-radius: 7px; border: 1px #dddddd solid; }

.info_fieldset legend
{
border: 1px #dddddd solid;
color: black; 

font: 13px Verdana;

padding: 2px 5px 2px 5px;
-moz-border-radius: 3px;
}

.button
{
border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

background: white;

color: #333333; 

font: 11px Verdana, Helvetica, Arial, sans-serif;

-moz-border-radius: 3px;
}

/* Label */
label  { width: 140px; padding-left: 20px; margin: 5px; float: left; text-align: left; }

/* Input, Textarea */
input, textarea
{
margin: 5px;
padding: 0px;
float: left;

border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

color: #333333; 

font: 11px Verdana, Helvetica, Arial, sans-serif;

-moz-border-radius: 3px;
}

/* BR */

br { clear: left; }

Step 3 - Creating the html contact page

This is the page where the AJAX call to contact.php is made. I will explain you the JavaScript Code in detail below:

contact.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>TableLess Ajax Contact Form (Demo)</TITLE>
  <META NAME="Keywords" CONTENT="form, divs">

  <META NAME="Description" CONTENT="A CSS Tableless Ajax Contact Form">

<!-- JQuery -->
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>

 <script type="text/javascript">
   // we will add our javascript code here           

$(document).ready(function(){
$("form").submit(function(){

// 'this' refers to the current submitted form
var str = $(this).serialize();

   $.ajax({
   type: "POST",
   url: "contact.php",
   data: str,
   success: function(msg){

$("#note").ajaxComplete(function(event, request, settings){

if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
}
else
{
result = msg;
}

$(this).html(result);

});

}

 });

return false;

});

});

 </script>  

<link rel="stylesheet" type="text/css" href="style.css" />

</HEAD>

 <BODY>

 <center>

<center><h3>A Tableless Contact Form (JQuery & AJAX)</h3></center>

<div align="left" style="width: 500px;">

<fieldset class="info_fieldset"><legend>Contact</legend>

<div id="note"></div>
<div id="fields">

<form action="javascript:alert('success!');">
<label>Name</label><INPUT class="textbox" type="text" name="name" value=""><br />

<label>E-Mail</label><INPUT class="textbox" type="text" name="email" value=""><br />

<label>Subject</label><INPUT class="textbox" type="text" name="subject" value=""><br />

<label>Comments</label><TEXTAREA class="textbox" NAME="message" ROWS="5" COLS="25"></TEXTAREA><br />

<label>&nbsp;</label><INPUT class="button" type="submit" name="submit" value="Send Message">
</form>

</div>

</fieldset>

</div>

 </center>

 </BODY>
</HTML>

Once the DOM is loaded (we determine this by using $(document).ready()), the script checks if the user submitted the form by using $("form").submit(). If it is, the form elements (names & values) are serialized in order to pass them to the AJAX Call:

var str = $("form").serialize();

$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request, and returns the XMLHttpRequest object for post-processing (like manual aborting) if needed.

Some options are used to control the behaviour of $.ajax. The information is from JQuery Documentation:

(String) type - This is to determine the type of request that is made: ‘POST’ or ‘GET’. (default is ‘GET’)
(String) url - The URL to request
(Object|String) data - Data to be sent to the server. It is converted to a query string, if not already a string. Is appended to the url for GET-requests. See processData option to prevent this automatic processing.
(Function) success - A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the ‘dataType’ parameter.

To find out more about $.ajax consider visiting http://docs.jquery.com/API/1.1/AJAX.

The request succeded? In this case we will call the ajaxComplete(callback) function, which executes whenever an AJAX request is completed. The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

If ‘OK’ is returned the form hides and a thank you message is shown. Otherwise, the script will show the errors.

    $.ajax({
    type: "POST",
    url: "contact.php",
    data: str,
    success: function(msg){  

 $("#note").ajaxComplete(function(event, request, settings){  

 if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
 {
 result = '<div class="notification_ok">Your message has been sent. Thank you!'</div>';
 $("#fields").hide();
 }
 else
 {
 result = msg;
 }
 $(this).html(result);
 });
 }  

  });

In the next page of our tutorial we will create: functions.php (which has the e-mail address validator) and contact.php (which is the script that parses the submitted data).

 The archive is made using WinZip 12.0. If you're having problems unzipping it, consider using WinRar, WinAce or a similar software to extract the files from the archive.

Be notified when we have new posts by subscribing to  RSS BitRepository RSS Feed.
   Save to StumbleUpon   

Similar entries

53 Responses to “A simple AJAX (Contact) Form with Validation (JQuery)”

  1. This is what I have:

    $message = "- Name: ".$name."\n- Phone: ".$phone."\n\n".$message; htmlspecialchars($_POST['message']);

  2. No, that is wrong! I told you to add the new line before the call to mail() (just after if(!$error) ) without any other changes.

  3. Ohhh. Im sorry lol. I misunderstood. Okay I tried that now it works!!

    =) Thanks alot for all your help!


Comment on this post!

Subscribe to BitRepository RSS Feed
[Advertise with us]