Ajax contact form using captcha validation

Hi, friends today I am teaching you how to send contact form with captcha using Ajax, jQuery and PHP. Contact form is very common application for every website. Here I build a quick contact form using ajax with all fields validation. I make it more secure using captcha. So there is no change for spamming. Lets build our application:

Step 1: In this step I create contact form for user from where they will send contact to us

<?php
$num1 = rand(1,10);
$num2 = rand(1,10);
$sum = $num1 + $num2;
?>
<!DOCTYPE html>
<html lang="en"><!-- This is a demonstration of HTML5 goodness with healthy does of CSS3 mixed in --><head>
    
    <title>Ajax contact form using captch in PHP</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--[if IE]>
    	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link rel="stylesheet" href="style.css" type="text/css" media="screen">
	<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
	<script type="text/javascript" src="js/send_data.js"></script>
</head>
<body>
   <div  class="cover">	
		<div id="result"></div>
		<div id="contactform"> 
			<p class="contact"><label for="name">Name</label></p> 
			<input id="name" name="name" placeholder="Yourname" type="text"> 
			 
			<p class="contact"><label for="email">Email</label></p> 
			<input id="email" name="email" placeholder="admin@admin.com" type="text"> 
			
			<p class="contact"><label for="Subject">Subject</label></p> 
			<input id="subject" name="subject" placeholder="Subject" type="text"> 
			 
			<p class="contact"><label for="comment">Your Message</label></p> 
			<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
			<p class="contact"><label for="captch"><?php echo $num1 ?>&nbsp;&nbsp;<span style="font-size:25px;">+</span>&nbsp;&nbsp;<?php echo $num2; ?></label>&nbsp;&nbsp;:&nbsp;&nbsp;<input id="captch" name="captch" type="text" style="width:360px;"> </p> 
			<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
			<input type="hidden" name="captch_value" id="captch_value" value="<?php echo $sum ;?>" />
		</div> 
    </div>       
</body>
</html>

Step 2: In this setp I create a style.css for styling our form



@font-face {
    font-family: 'YanoneKaffeesatzRegular';
    src: url('fonts/YanoneKaffeesatz-Regular-webfont.eot');
    src: url('fonts/YanoneKaffeesatz-Regular-webfont.eot?#iefix') format('embedded-opentype'),
         url('fonts/YanoneKaffeesatz-Regular-webfont.woff') format('woff'),
         url('fonts/YanoneKaffeesatz-Regular-webfont.ttf') format('truetype'),
         url('fonts/YanoneKaffeesatz-Regular-webfont.svg#YanoneKaffeesatzRegular') format('svg');
    font-weight: normal;
    font-style: normal;
}
@font-face {
    font-family: 'BebasNeueRegular';
    src: url('fonts/BebasNeue-webfont.eot');
    src: url('fonts/BebasNeue-webfont.eot?#iefix') format('embedded-opentype'),
         url('fonts/BebasNeue-webfont.woff') format('woff'),
         url('fonts/BebasNeue-webfont.ttf') format('truetype'),
         url('fonts/BebasNeue-webfont.svg#BebasNeueRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}
body, div, h1, form, fieldset, input, textarea {
	margin: 0; padding: 0; border: 0; outline: none;
}
html {
	height: 100%;
	/* overflow: hidden; */
}
body {
	font-family: sans-serif;
}
.cover{
	background:#000; width:700px; margin:auto; padding-left:60px;
}
p.contact { font-size: 18px; margin-bottom: 15px; font-family: 'BebasNeueRegular', Arial; color: #4b4b4b; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);margin-top:0; }
#contact { margin-bottom: 0px; }
input{ width: 400px; }
textarea { width: 600px; height: 150px; }
label { color: red; }
input, textarea { background-color: rgba(255, 255, 255, 0.4); border: 5px solid rgba(122, 192, 0, 0.15); padding: 10px; font-family: Keffeesatz, Arial; color: #ffffff; font-size: 12px; -webkit-border-radius: 5px; margin-bottom: 15px; margin-top: -10px; }
/*input:focus, textarea:focus { border: 5px solid #ff5400; background-color: rgba(255, 255, 255, 1); }*/

input[type="submit"] { border: none; cursor: pointer; color: #fff; font-size: 24px; background-color: #7ac000; -webkit-border-radius: 10px; -moz-border-radius: 10px; -webkit-box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.4); -moz-box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.6); border-bottom: 1px solid rgba(0, 0, 0, 0.4); border-top: 1px solid rgba(255, 255, 255, 0.6);
	background: -webkit-gradient(
	    linear,
	    left bottom,
	    left top,
	    color-stop(0.23, #619702),
	    color-stop(0.62, #7ac000)
	);
	background: -moz-linear-gradient(
	    center bottom,
	    #619702 23%,
	    #7ac000 62%
	);
}

input[type="submit"]:hover { color: #fff; border-bottom: 1px solid rgba(0, 0, 0, 0.4); background-color: #ff5400;
	background: -webkit-gradient(
	    linear,
	    left bottom,
	    left top,
	    color-stop(0.23, #c34000),
	    color-stop(0.62, #ff5400)
	);
	background: -moz-linear-gradient(
	    center bottom,
	    #c34000 23%,
	    #ff5400 62%
	);
}
input[type="submit"]:active { top: 1px; }
#result{
	color: #ffffff;
    font-size: 20px;
    line-height: 50px;
}
.error{color:red;}
.success{color:green;}

Step 3: Now I create a send_mail.js for taking value after clicking “Send Mail” button. This js file take the value from the form , validate all fields and send all data to another php file using ajax post request

$(document).ready(function(){
	$("#submit").click(function() { 
		//get input field values
		var name       		= $('#name').val(); 
		var email      		= $('#email').val();
		var subject    		= $('#subject').val();
		var message   	    = $('#comment').val();
		var captch          = $('#captch').val();
		var captch_value	= $('#captch_value').val();
		var flag = true;
		/********validate all our form fields***********/
        if(name==""){ 
            $('#name').css('border-color','red'); 
            flag = false;
        }
        if(email==""){ 
            $('#email').css('border-color','red'); 
            flag = false;
        } 
		if(subject==""){ 
            $('#subject').css('border-color','red'); 
            flag = false;
        }
        if(message=="") {  
           $('#comment').css('border-color','red'); 
            flag = false;
        }
		if(captch=="") {  
           $('#captch').css('border-color','red'); 
            flag = false;
        }
		/********Validation end here ****/
		/********Validate captch********/
		if(captch != captch_value){
			$('#captch').css('border-color','red'); 
            flag = false;
		}
		/*************************/
		/* If all are ok then we send ajax request to email_send.php *******/
		if(flag) 
        {
			$.ajax({
				type: 'post',
				url: "email_send.php", 
				dataType: 'json',
				data: 'username='+name+'&useremail='+email+'&subject='+subject+'&message='+message,
				beforeSend: function() {
					$('#submit').attr('disabled', true);
					$('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
				},
				complete: function() {
					$('#submit').attr('disabled', false);
					$('.wait').remove();
				},	
				success: function(data)
				{
					if(data.type == 'error')
					{
						output = '<div class="error">'+data.text+'</div>';
					}else{
						output = '<div class="success">'+data.text+'</div>';
						$('#contactform input').val(''); 
						$('#contactform textarea').val(''); 
					}
					
					$("#result").hide().html(output).slideDown();			
					}
			});
		}
	});

	//reset previously set border colors and hide all message on .keyup()
	$("#contactform input, #contactform textarea").keyup(function() { 
		$("#contactform input, #contactform textarea").css('border-color',''); 
		$("#result").slideUp();
	});
});

Step 4: Last step for our application. Here I create a email_send.php which takes all ajax post data, validate all data using php, if any error occurs, send it to the ajax file with error message. If all are ok then I send a success message to ajax file. I display the message using result id.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{

	//check if its an ajax request, exit if not
	if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
	
		//exit script outputting json data
		$output = json_encode(
		array(
			'type'=>'error', 
			'text' => 'Request must come from Ajax'
		));
		
		die($output);
	} 
	
	//check $_POST vars are set, exit if any missing
	if(!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["subject"]) || !isset($_POST["message"]))
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
		die($output);
	}

	//Sanitize input data using PHP filter_var().
	$username       = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
	$useremail      = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
	$subject        = filter_var(trim($_POST["subject"]), FILTER_SANITIZE_STRING);
	$message        = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
	
	//additional php validation
	if(strlen($username)<4) // If length is less than 4 it will throw an HTTP error.
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Name is too short!'));
		die($output);
	}
	if(!filter_var($useremail, FILTER_VALIDATE_EMAIL)) //email validation
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
		die($output);
	}
	if(strlen($subject)<4) // If length is less than 4 it will throw an HTTP error.
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Subject is too short!'));
		die($output);
	}
	if(strlen($message)<5) //check emtpy message
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Too short message!'));
		die($output);
	}
	
	$to   	= "abhijitscom@gmail.com"; //Replace with recipient email address
	//proceed with PHP email.
	$headers = 'From: '.$useremail.'' . "\r\n" .
	'Reply-To: '.$useremail.'' . "\r\n" .
	'X-Mailer: PHP/' . phpversion();
	
	$sentMail = @mail($to, $subject, $message .'  -'.$username, $headers);
	
	if(!$sentMail)
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please contact administrator.'));
		die($output);
	}else{
		$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$username .' Thank you for your email'));
		die($output);
	}
}
?>

Demo
Download

Spread the love
  •  
  •  
  •  
  • 0
  •  
  •  
  •  
  •  
  •  
  •