Ajax based contact form with captcha demo and example
To demonstrate Ajax based form submission without refreshing the page contact form will be best and easy example as it has few and general input fields, moreover we can make it more secure implementing captcha etc.
Before starting have a look at running demo on completing this tutorial we will end up with form like available at this live demo
Here in this article to keep things simple and easy to understand we will
- Start from simple form submission by traditional method
- After that we will make it ajax based
- And then at last we will implement captcha into it
First of all as we will be saving user message into database table, so to create table run this query in your database to create table named tbl_contacts
1 2 3 4 5 6 7 8 9 |
CREATE TABLE `tbl_contacts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `company` varchar(255) NOT NULL, `phone` varchar(255) NOT NULL, `message` text NOT NULL, PRIMARY KEY (`id`) ) |
Now create a php file name it contact.php and paste the following simple html code in it, this file will display contact form with fields name, email, company, phone and message.
contact.php
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Ajax based contact form| Demos by Alam</title> <meta name="Keywords" content="alam, developer, demo, code, tests, links, fakhr-e-alam"> <meta name="Description" content="Ajax based simple contact form demonstration."> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> </head> <body> <div class="container"> <h1 class="text-center">Ajax based contact form</h1> <p class="text-center small">This is Demo by Alam. Visit <a href="http://www.codingsips.com">Coding Sips</a> for more Coding tips</p> <div class="jumbotron"> <a class="label label-info pull-right" href="http://www.codingsips.com/generate-qr-code-easily-one-line-php/" target="_blank">Tutorial: Ajax based contact form</a> <br> <form action="save-contact.php" method="POST" id="contact-frm"> <div class="row"> <div class="col-xs-12 col-sm-6"> <div class="form-group"> <label for="txtName">Name</label> <input type="text" id="txtName" name="txtName" class="txt form-control" required /> </div> </div><!--.col--> <div class="col-xs-12 col-sm-6"> <div class="form-group"> <label for="txtEmail">Email</label> <input type="email" id="txtEmail" name="txtEmail" class="txt form-control" required /> </div> </div><!--.col--> </div><!--.row--> <div class="row"> <div class="col-xs-12 col-sm-6"> <div class="form-group"> <label for="txtCompany">Company</label> <input type="text" id="txtCompany" name="txtCompany" class="txt form-control" /> </div> </div><!--.col--> <div class="col-xs-12 col-sm-6"> <div class="form-group"> <label for="txtPhone">Phone</label> <input type="text" id="txtPhone" name="txtPhone" class="txt form-control" /> </div> </div><!--.col--> </div><!--.row--> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <label for="txtMessage">Message</label> <textarea rows="5" id="txtMessage" name="txtMessage" class="txt form-control" required></textarea> </div> </div><!--.col--> </div><!--.row--> <!--captcha code will come here--> <div class="row"> <div class="col-xs12 col-sm-6"> <input type="submit" value="Send Message" class="btn btn-success" /> </div><!--.col--> <div class="col-xs12 col-sm-6"> <div class="result"></div><!--.result--> </div><!--.col--> </div><!--.row--> </form> </div><!--.jumbotron--> </div><!--.container--> </body> </html> |
if we open this file in browser, it will display a form like the following snapshot.
Now we will be writing its back-end coding to catch the data submitted and save it in database table. To do so we have to
- Create database connection
- Check if POST request is made
- Grab POST variables, clean it (escape special chars) and assign it to variables
- Make insert query
- Execute query
- Display success or error message
create another php file name it save-contact.php and paste the following code into it. all the code below is explained by comments and list of steps given above.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?php //connect to database $db_host = "localhost"; $db_user = "root"; $db_pwd = ""; $db_name = "test"; $db= new mysqli($db_host,$db_user,$db_pwd,$db_name); if($db->connect_error) { echo "ERROR: (".$db->connect_errno.") ".$db->connect_error; exit(); } //check if POST request is made(via normal for submission or ajax) if($_POST){ //insert record insert_record(); }//end if post /*function to insert data in table*/ function insert_record(){ //access $db inside function global $db; //collect post variable data $name = clean($_POST['txtName']); $email = clean($_POST['txtEmail']); $company = clean($_POST['txtCompany']); $phone = clean($_POST['txtPhone']); $message = clean($_POST['txtMessage']); //make query $qry = 'insert into tbl_contacts (name,email,company,phone,message) values( "'.$name.'", "'.$email.'", "'.$company.'", "'.$phone.'", "'.$message.'" )'; //echo $qry; /*debug qry*/ if($result = $db->query($qry)){ echo 'Message sent successfully, we will get in touch with you soon.'; }else{ echo 'ERROR : '. $db->error; } }//end insert_record() /*function to escape special chars to prevent sql injection */ function clean($str){ global $db; return $db->real_escape_string($str); }//end clean() ?> |
If we submit the form it will insert a record in tbl_contacts this was the traditional method of form submission, Now we will be submitting the same form using ajax to do so first of all write a line before ending tag in contact.php to link our script file named myscript.js
1 |
<script type="text/javascript" src="myscript.js"></script> |
Now create a js file name it myscript.js and paste the following code in it.
myscript.js
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
$(function(){ //captcha refresh code will come here $('#contact-frm').submit(function(e){ //prevent default fuctionality of form submision e.preventDefault(); //make ajax post request $.ajax({ url:'save-contact.php', type:'post', data:{ txtName : $('#txtName').val().trim(), txtEmail : $('#txtEmail').val().trim(), txtCompany: $('#txtCompany').val().trim(), txtPhone : $('#txtPhone').val().trim(), txtMessage: $('#txtMessage').val().trim(), }, beforeSend:function(){ display_msg('Wait: Processing','info'); }, success:function(response){ if(response.toLowerCase().indexOf('error')>=0){ display_msg(response,'danger'); }else{ display_msg(response,'success'); //reset form inputs $('#contact-frm')[0].reset(); //captcha reset code comes here } }, error:function(){ display_msg('Some error occured','danger'); /* visit http://www.codingsips.com/ajax-with-error-handling for detailed error handling */ } }); }); }); function display_msg(str,type){ //str = error or success message //type = for success green, for error red $('.result').html('<div class="alert alert-'+type+'">'+str+'</div>').slideDown(); }//end display_msg() |
It was all for basic and simple ajax form submission, if you understood above coding 100% then read the next and last portion of implementing captcha in Ajax based contact form, else read and practice it from start until you understand all above code.
To implement captcha in this form we have to do the following things step by step
- Crate a php file to develop captcha image for which we will also need a font_file.ttf
- Show Captcha in contact.php as image and add an extra textbox so that user can enter captcha word
- In myscript.js along with other variables we will have to send captcha word entered by user
- And finally at save-contact.php we will have to verify captcha and than process accordingly
To study captcha coding in detail read my previous article on How to create custom captcha, for now create a php file name it captcha.php and paste the following code in it
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?php session_start(); function generateCode($characters=4) { /* list all possible characters, similar looking characters(1,i,l) and vowels have been removed to avoid real words */ $possible = '23456789bcdghjkmnpqrstvwyz'; $code = ''; for ($i=0;$i < $characters;$i++) { $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1); } return $code; } function create($characters=4,$width='120',$height='35') { /*get random string */ $code = generateCode($characters); $font = 'alam_font.ttf'; /* font size will be 75% of the image height */ $font_size = $height * 0.75; $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream'); /* set the colours */ $background_color = imagecolorallocate($image, 220, 220, 220); $text_color = imagecolorallocate($image, 10, 30, 80); $noise_color = imagecolorallocate($image, 150, 180, 220); /* generate random dots in background */ for( $i=0; $i<($width*$height)/3; $i++ ) { imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color); } /* generate random lines in background */ for( $i=0; $i<($width*$height)/150; $i++ ) { imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color); } /* create textbox and add text */ $textbox = imagettfbbox($font_size, 0, $font, $code) or die('Error in imagettfbbox function'); $x = ($width - $textbox[4])/2; $y = ($height - $textbox[5])/2; $y -= 5; imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code) or die('Error in imagettftext function'); /* output captcha image to browser */ header('Content-Type: image/jpeg'); imagejpeg($image); imagedestroy($image); /*put string in session*/ $_SESSION['alam_captcha']=$code; } /*call create() function to generate captcha*/ create(); ?> |
Copy alam_font.ttf font file to your project directory and check the following url, it must show captcha
1 |
http://localhost/your-project-name/captcha.php |
Now open contact.php and locate a comment it is before submit button, paste the following lines of code at location of above comment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="row"> <div class="col-xs12 col-sm-3 col-md-2"> <img id="img-captcha" alt="captcha" src="captcha.php" /> </div><!--.col--> <div class="col-xs12 col-sm-3 col-md-2"> <label for="txtCaptcha">Enter Captcha</label> </div><!--.col--> <div class="col-xs12 col-sm-3 col-md-2"> <div class="form-group"> <input type="text" id="txtCaptcha" name="txtCaptcha" class="txt form-control" required placeholder="Enter captcha" /> </div> </div><!--.col--> <div class="col-xs12 col-sm-3 col-md-6"> <button id="refresh-captcha" class="btn btn-info btn-xs">Try another captcha</button> </div><!--.col--> </div><!--.row--> |
It will display captcha and textbox to enter captcha in form as shown in below snapshot
Open myscript.js after line 16 txtMessage: $(‘#txtMessage’).val().trim(), before closing curly brace, write the following line.
1 |
txtCaptcha: $('#txtCaptcha').val().trim(), |
Now to refresh captcha we have to write a function in myscript.js copy the following code and paste it at line 2 of myscript.js
1 2 3 4 5 |
$('#refresh-captcha').click(function(e){ e.preventDefault(); var d = new Date(); $('#img-captcha').attr('src','captcha.php?'+d.getTime()); }); |
when form is successfully submitted the form is getting reset means all text-boxes are getting empty, along with this captcha should also be refreshed and display new captcha. To do so wite the following link on code in success function inside myscript.js replacing comment captcha reset code comes here just after form resetting at line about 28.
1 |
$('#refresh-captcha').trigger('click'); |
Finally open save-contact.php as we will be checking captcha with session variable so at top of the page after php starting tag write the following line
1 |
session_start(); |
and replace line 16-21 if statement with the following code.
1 2 3 4 5 6 7 8 9 10 |
//check if POST request is made(via normal for submission or ajax) if($_POST){ if(strtolower($_SESSION['alam_captcha'])==strtolower($_POST['txtCaptcha'])){ //insert record insert_record(); }else{ echo 'ERROR: Invalid captcha entered.'; } }//end if post |
Its all done, if you have not made any mistake will work fine without any error. If you are getting error try and follow the article from beginning. If still have issue write your errors at comments we will try our best to help you.
For demonstration I have skipped designing and form validation etc to reduce amount of code and keep it clean and easier to understand. after successfully completing few times you can customize its design and implement decent validation etc.
A running demo of this tutorial can be found at this link Live demo: ajax based simple contact form with captcha
Comments