Last Updated on January 22, 2023 by Roshan Parihar
Learn how to create PHP ajax contact form with a captcha and validation. Submit the form to collect users’ data without page refresh using jQuery ajax.
You can easily create a contact form design using Bootstrap pre-defined CSS classes. To use Bootstrap classes, you have to just include its libraries to start using it on your contact form design.
Looking to create contact forms to send emails without page refresh and coding? Create beautiful-looking contact forms with JotForm.
The jQuery ajax contact form validates the users entered code with our captcha code. After the captcha validation success, it sends an email message to the website owner. You will get a success message on each valid entry and an error message on invalid entries.
In this post, I am going to show you how to create a contact form design using Bootstrap and add a captcha to it using PHP.
After that, you will get the jQuery ajax code to submit the form and refresh the captcha code without the page. You will also get PHP code to validate the form data and send emails to the website owner.
So, let’s get started.
PHP Ajax Contact Form with Captcha and Validation
Here is the step-by-step process to help you easily create a PHP Ajax contact form with a captcha:-
Step 1: PHP Captcha Image Creation
The first step is to create a captcha image of code using PHP to add to your contact form. To create a captcha image code, you have to start a session to store the captcha code. After that, create a randomly generated 6-digit captcha code using rand()
with md5 encryption.
The below PHP code will generate a captcha image when you run it on your browser. Each time you refresh this page on your browser, you will get a different captcha code.
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 |
<?php //Start session session_start(); //Generate random number with md5 encryption $captcha = md5(rand(1000, 9999)); //Get 6 digits encrypted main captcha code from a random number $captcha_code = substr($captcha, 0, 6); //Store captcha in session $_SESSION['captcha'] = $captcha_code; //Generate standard captcha image $captcha_img = imagecreatetruecolor(65, 27); //Background color $captcha_bg = imagecolorallocate($captcha_img, 22, 86, 165); //Give captcha image a background imagefill($captcha_img, 0, 0, $captcha_bg); //foreground color $captcha_fg = imagecolorallocate($captcha_img, 255, 255, 255); //Print captcha text in the image with a random position and size imagestring($captcha_img, 7, 7, 5, $captcha_code, $captcha_fg); //Prevent browser cache header("Cache-Control: no-store, no-cache, must-revalidate"); //Render this PHP file as an image header('Content-type: image/png'); //Show the captcha as a PNG image on the browser imagepng($captcha_img); ?> |
The code contains useful comments to easily understand the use of each code and learn to create the captcha code using PHP.
Now, your captcha code is ready. Let’s create a beautiful contact form design using Bootstrap 5 and add this captcha code image to it.
Step 2: Create Contact Form Design Using Bootstrap 5 with Captcha Image
Bootstrap is the mobile-first and most useful responsive framework. You can use it to easily create mobile-friendly contact form designs for your website.
To start using Bootstrap 5 classes work for you, you have to include its style CDN URL as given below. You have to include it in the <head>
section of your HTML contact form design code.
1 |
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> |
We are also going to use font awesome icons and jQuery script. To font awesome icons and jQuery script work for you, you have to include the below CDN URLs to the <head>
section.
1 2 |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.js"></script> |
Now, after adding the above CDN URLs, you can create your contact form design and make the captcha code work. Below is the complete code of the final design of the contact form with the captcha code.
You can use the below code to get the exact design whose image is shown after the below code.
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 |
<!doctype html> <html lang="en"> <head> <title>PHP Ajax Contact Form Design Using Bootstrap 5</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.js"></script> <style> .loader_icon{ background: #0404046b; display: flex; justify-content: center; align-items: center; position: fixed; left: 0; top: 0; width: 100%; height: 100%; } .loader_icon i{ font-size: 24px; color: #fff; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 offset-md-3 mt-3 bg-light p-3 border border-secondary"> <!-- Bootstrap main form start --> <form method="POST" id="ajaxform"> <div class="mb-3"> <label for="Name" class="form-label">Your Name</label> <input type="text" class="form-control" name="name" placeholder="Enter name" required> </div> <div class="mb-3"> <label for="Email" class="form-label">Your Email</label> <input type="email" class="form-control" name="email" placeholder="Enter email" required> </div> <div class="mb-3"> <label for="message" class="form-label">Message</label> <textarea class="form-control" name="message" placeholder="Enter your message" rows="5" required></textarea> </div> <div class="mb-3"> <label for="Captcha">Captcha</label> <input type="text" class="form-control" name="captcha" id="captcha" required> <img id="captcha_code_img" src="captcha.php" /> <a href="#" id="captcha_refresh_btn"><i class="fa fa-refresh" aria-hidden="true"></i></a> </div> <input type="submit" class="btn btn-primary" name="submit" value="Submit"> </form> <!-- Bootstrap main form end --> <br> <div id="form_message"></div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <div class="loader_icon" style="display:none;"><i class="fa fa-spinner fa-spin"></i></div> </body> </html> |
The contact form contains all the important fields useful to make communicate with your audience. It also contains the captcha code to validate with the user’s entered code. Captcha is an important part of contact forms to stop spam bots fill them.
Let’s add a jQuery ajax script to submit the form without page refresh. The script can also refresh the jQuery ajax code.
Step 3: jQuery Ajax Contact Form Submission with Captcha Code Refresh
jQuery ajax is useful to submit the form and update some parts of the page without page refresh after form submission. You have to place the below code just before the </body>
close tag to make it work on your contact form.
To refresh the captcha, the below script uses the PHP file ‘captcha.php’ that contains the captcha image generation script. As the captcha code is an image, you have to use jQuery attr()
to update the source of the image as given below.
The below ajax submission script sends form data to the PHP file ‘send-email.php’. This file contains the PHP script to validate form data and captcha image code. If the data and captcha code is showing valid, it allows submission of the form to send emails to the owner of the website.
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 |
<script> //Script to refresh the captcha $(document).ready(function(){ $('#captcha_refresh_btn').click(function(){ $("#captcha_code_img").attr('src', 'captcha.php'); }); }) </script> <script> //script to submit for using ajax without page refresh $("#ajaxform").submit(function(e) { e.preventDefault(); // avoid executing the actual submission of the form var form = $(this); $(".loader_icon").show(); $.ajax({ url: "send-email.php", global: false, type: "POST", data: form.serialize(), // serializes the form's elements. success: function(data) { $('div#form_message').html(data); $(".loader_icon").hide(); } }); }); </script> |
The jQuery ajax code sends the form data in serialization and submits the form with the post method. You will also get notification messages below the form after the successful submission of the form.
Step 4: PHP Code to Send Emails with Captcha Validation
To make PHP ajax contact form work, you have to add the simple PHP code given below. It first collects all the form data including the captcha code. As we have made all the input required using the HTML inbuilt required
attribute. So, there is no need to manually make fields required.
However, the only thing we have to validate is the email address and the captcha code to match the users entered email and captcha code. The below code contains the email validation to get the correct email address from your users.
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 |
<?php //start session to match with captcha session variable session_start(); //Get form data $captcha = $_POST['captcha']; $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; //validation for email $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { ?> <div class="alert alert-success alert-dismissible fade show"> The Email address you entered is not valid. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php exit; } //Match with captcha session data if($captcha == $_SESSION['captcha']){ $subject = "Contact Form"; //Subject of the email //Message content to send in an email $message = "Name: ".$name."<br>Email: ".$email."<br> Message: ".$message; // Set content type as HTML $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; //Email headers $headers .= "From:".$email."\r\n"; //$headers .= "CC: [email protected]"; $headers .= "Reply-To:".$email."\r\n"; //Send email $sendmail = mail($to, $subject, $message, $headers); if($sendmail == true){ ?> <div class="alert alert-success alert-dismissible fade show"> The message has been sent successfully. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php }else { ?> <div class="alert alert-danger alert-dismissible fade show"> The message could not be sent. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php } }else{ ?> <div class="alert alert-danger alert-dismissible fade show"> Captcha is not matching. Please enter the correct captcha code. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php } ?> |
After email validation, the code checks the captcha code if matching with the user’s entered captcha code in the input box. When it found the captcha code matching with the users entered code, the next PHP code will execute to send data in an email to the receiver.
You will also get an error and success message designed using Bootstrap 5. The success message will display in green color while the error message will display in red color.
That’s all about PHP ajax contact form.