Jul 25, 2012

AJAX Contact Form With Validation

Today I am going to share a simple tutorial on How to make a AJAX contact form with validation.

JQUERY-AJAX



What is AJAX?
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


The flow of the form is :


AJAX Process Diagram

So here I am using twitter bootstrap, so files which we need are :-

  • data.php - (here we will write our PHP code)

  • script.js - (here we will write our ajax jquery code)

  • validate.js - (jqueryvalidation plugin)

  • index.php and style.css



So the fields of our form will be Name, Email, Number, City, Area, Message, Submit

Here our city and area will also be using AJAX i.e. on city change area will also be changed.

index.php


[html]
<?php require_once('data.php'); ?>
<div class="hero-unit">
<h2>Contact Us</h2>

<form id="contactUs" name="contactUs" onsubmit="return false;">


<table cellspacing="5" cellpadding="5">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" value="" name="name" id="name" class="required name"/></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" value="" name="email" id="email" class="required email"/></td>
</tr>
<tr>
<td><label for="number">Contact Number:</label></td>
<td><input type="text" value="" name="number" id="number" class="required number" minlength="8"/></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td>
<select id="city" name="city" onchange="javascript:changeArea('#city', '#area');">
<option value="Any">Any</option>
<?php echo getCities();?>
</select>
</td>
</tr>
<tr>
<td><label for="area">Area:</label></td>
<td><select id="area" name="area" disabled="disabled"></select></td>
</tr>
<tr>
<td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" class="required"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="contactFormSubmit" value="Yes" />
<input type="submit" value="Submit" class="btn" onclick="javascript:formSubmit('#contactUs','#responseText');"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<div id="responseText"></div>
</td>
</tr>

</form>
</div>
[/html]



Here we just made a simple html structure of form inside a table.

To make a field mandatory, just add class="required" to input.

If you want to validate it with only email or number then add class="required email" or class="required number"

If I add a attribute minlength="8" to the number field then that field should contain at least 8 digits of number.

data.php


[php]
<?php
$cities = array('1'=>'Mumbai',
'2'=>'Chennai',
'3'=>'Noida',
'4'=>'Bangalore');

$areas = array( 'Airoli' => '1',
'Andheri' => '1',
'Bandra' => '1',
'Bhandup' => '1',
'Bhayandar' => '1',
'Boisar' => '1',
'Borivali' => '1',
'Chembur' => '1',
'Gopalapuram' => '2',
'Mount Road' => '2',
'Noida Expressway' => '3',
'Sector 1' => '3',
' Sector 128' => '3',
'Sector 129' => '3',
'Yamuna Expressway' => '3',
'Anekal ' => '4',
'Banashankari ' => '4',
'Banasvadi ' => '4',
'Banaswadi ' => '4',
'Begur ' => '4',
'Bellary Road ' => '4',
'Dobespet ' => '4',
'Electronics City' => '4');


if(isset($_REQUEST['cityID']) && $_REQUEST['cityID'] != 'Any'){

getAreas($_REQUEST['cityID']);

}

if(isset($_REQUEST['contactFormSubmit'])){
if(!isValidEmail($_REQUEST['email'])){
echo 'Enter a valid email ID';
}elseif(!is_mobileNumber($_REQUEST['number'])){
echo 'Enter a valid number';
}elseif($_REQUEST['name'] == '' || $_REQUEST['message'] == ''){
echo 'Enter valid name or message';
}else{
?>
<p><b>Thank you for contacting us, your given information : </b></p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td>Name:</td>
<td><?php echo $_REQUEST['name']?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $_REQUEST['email']?></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><?php echo $_REQUEST['number']?></td>
</tr>
<tr>
<td>City:</td>
<td><?php echo $_REQUEST['city']?></td>
</tr>

<?php if(isset($_REQUEST['area'])) : ?>
<tr>
<td>Area:</td>
<td><?php echo $_REQUEST['area']?></td>
</tr>
<?php endif; ?>

<tr>
<td>Message:</td>
<td><?php echo $_REQUEST['message']?></td>
</tr>
</table>
<?php
}
}



function getCities(){
global $cities;
foreach($cities as $Idx => $city){

echo '<option value="'.$Idx.'">'.$city.'</option>';

}
}

function getAreas($cityID = ''){
global $areas;
foreach($areas as $area => $Idx){

if($Idx == $cityID){

echo '<option value="'.$Idx.'">'.$area.'</option>';

}

}
}

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

function is_mobileNumber($mobile) {
$regex1 = '123456789';
$regex2 = '1234567890';
$regex3 = '0123456789';

if(preg_match('/^([0-9])\1*$/', $mobile)){
return false;
}elseif($mobile == $regex1){
return false;
}elseif($mobile == $regex2){
return false;
}elseif($mobile == $regex3){
return false;
}elseif(preg_match("/[^0-9]/", $mobile)){
return false;
}else{
return true;
}
}
?>
[/php]



PHP code is simple, I am making an array of cities and area, made 2 functions to get areas and cities and getting the parameters from URL and passing it to functions.

Now the ajax function :

script.js


[js]
function changeArea(cityBox, areaBox) {
jQuery(function($) {

$(areaBox).attr('disabled','disabled');

$(areaBox).addClass('loading');
$.ajax({ //Starting the AJAX
url : 'data.php', //File to be called or pass the data
data : { //Extra paramters
"cityID" : $(cityBox+' option:selected').attr('value')
},
success : function(data) { // The result from data.php file comes as data
window.setTimeout(function(){
$(areaBox).removeAttr('disabled');

$(areaBox).removeClass('loading');

$(areaBox).html('');

$(areaBox).html(data);

}, 2000);
}
});
});
}
[/js]



The above function is is taking two parameters, the select id of City and area. Then I am saving the value of city in a variable, and inside ajax I am passing the value of city to data.php file.

Inside data.php I wrote a function to return areas according to the city ID. Inside success function I am inserting entire result into the area select box.

Simlarly I am going to make another function which will validate the form and if no error then ajax is called and mail is sent.

script.js


[js]
/* Submission of form */

function formSubmit(formID, displayMssgID) {
jQuery(function($) {

var qstring = $(formID).serialize();

var val = $(formID).validate().form();
if (val) {
$(displayMssgID).html('Registering your Request ... Please Wait ...');
$.ajax( {
url : "data.php",
data : qstring,
success : function(data) {

$(displayMssgID).html('');
$(displayMssgID).html(data);
window.setTimeout(function() {

$(displayMssgID).fadeOut();

}, 6000);

}
});
}
});
}
[/js]



This function takes two parameters, ID of the form and result message div. First I am serializing the form, which will take all the form data and store it in a variable. Then I am validating it, if validation is true then our AJAX is called and entire form data is passed to data.php file.

This is return will give some output which I am showing it in id="responseText"

This is a simple way to make AJAX forms, there might be many other tutorials on other websites but I find this very simple. This way you can make any AJAX form. Try out the demo.



Thanks to Jacob for server validation tip.

6 comments :

  1. where does the form information get posted to? does it get sent via email to a specific email address or can it be stored in a file?

    ReplyDelete
  2. You can do anything with the information, you can store it into database or email it. Its all up to you, you can edit this in data.php file

    ReplyDelete
  3. Hi, can you post a php form handler that will work with this? It's great, validation works, but I am having difficulty getting it to send an email. I have tried different php scripts and changed the data.php file with no luck at this point.

    ReplyDelete
  4. I got it to validate and send, BUT, onsubmit="return false;" within the form tag causes it to fail. It will validate and send, but the info in the form fields are NOT sent, i.e., empty emails. Of course, if I leave it out, it sends with the form info, but, it reloads a blank page with the confirmation message instead of within the "responseText" div.


    Additionally, when I strip out all of the city stuff from the script (carefully), the PHP syntax seems to be incorrect.

    ReplyDelete
  5. Do you have a working demo where I can debug it?

    ReplyDelete
  6. sending mail is really simple, first set your mail settings, and then use simple php :

    ReplyDelete