How to Create PHP AJAX Contact Form with Google reCaptcha




Hello, in this tutorial we will create a simple PHP AJAX based contact form with Google reCaptcha. This tutorial assumes that you are good at PHP and jQuery. You can contact the author, if you need to add custom fields or consultancy regarding the topic. Let’s take a look on prerequisites before continuing to the tutorial.

Prerequisites

  • Bootstrap based HTML document along with jQuery
  • You need to get site key and secret key by registering your website in Google reCaptcha. make sure that you have both the site key and secret key.

Also read:

Steps to Create PHP Ajax Contact Form with Google reCaptcha

We assume that you already have a HTML document with bootstrap basic template. Let’s start-

  1. Insert the reCaptcha script in the header section
    <script src='https://www.google.com/recaptcha/api.js'></script>
    
  2. Create a HTML form tag with the id contactform, method post and action mailer.php
    <form id="contactform" method="post" action="mailer.php">
    
  3. Add the Name, Phone, Email and Message fields inside the form
    <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" name="username" placeholder="Enter your name">
    </div>
    
    <div class="form-group">
    <label for="phone">Phone</label>
    <input type="text" class="form-control" id="phone" name="phone" placeholder="Enter your phone number">
    </div>
    
    <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" id="email" name="email" placeholder="Enter your email address">
    </div>
    
    <div class="form-group">
    <label for="message">Message</label>
    <textarea class="form-control" id="message" name="message" rows="4" placeholder="Enter your email message"></textarea>
    </div>
    
  4. Place the reCaptcha div with your site key
    <div class="g-recaptcha" data-sitekey="SITE KEY"></div>
    
  5. Add the div with the id formresult for showing success or error message and also add submit and reset buttons
    <div id="formresult"> </div>
    
    <button type="submit" name="submit" class="btn btn-info">Submit</button>
    <button type="reset" class="btn btn-danger">Reset</button>
    
  6. Now let’s work on jQuery code, create a document ready function in the same HTML file and add a submit event for #contactform form with preventDefault() method
    $('#contactform').submit(function(event) {
    preventDefault();
    }
    
  7. Add the following variables inside the event
    var contactform = $('#contactform');
    var formresult = $('#formresult');
    var formdata = $(contactform).serialize();
    
  8. Now initiate the AJAX request to mailer.php
    $.ajax({
    type: 'POST',
    url: $(contactform).attr('action'),
    
    data: formdata,
    success:function(response) {
    $(formresult).removeClass();
    $(formresult).addClass('alert alert-success');
    $(formresult).html(response);
    },
    error:function(data) {
    $(formresult).removeClass();
    $(formresult).addClass('alert alert-warning');
    $(formresult).html(data.responseText);
    }
    
    });
    
  9. Now let’s code the mailer.php, first of all check whether request method is POST with the conditional statement
    if ($_SERVER["REQUEST_METHOD"] == "POST") {}
    
  10. Receive the form data with POST method and validate
    $name = trim($_POST["username"]);
    $phone = trim($_POST["phone"]);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);
    if(isset($_POST['g-recaptcha-response'])){
    $captcha = $_POST['g-recaptcha-response'];
    }
    
    //Validate the data
    if (empty($name) OR empty($phone) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($message) OR empty($captcha)) {
    http_response_code(400);
    echo " Please fill all the form inputs and check the captcha to submit.";
    exit;
    }
    
  11. Prepare the email
    //recipient email address.
    $recipient = "abc@example.com";
    $subject = "New message from $name";
    
    //email content.
    $email_content = "Name: $name\n";
    $email_content .= "Phone: $phone\n\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";
    //email headers
    $email_headers = "From: $name <$email>";
    
  12. Now we have to add the reCaptcha secret key and check whether Google reCaptcha is successful or not, if it is not successful then the form got submitted by a spam bot.
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR_SECRET_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
    $decoded_response = json_decode($response, true);
    if($decoded_response['success'] == true){
    
    // Send the email.
    
    if (mail($recipient, $subject, $email_content, $email_headers)) {
    http_response_code(200);
    echo " Thank You! Your message has been sent.";
    } else {
    http_response_code(500);
    echo "Whoa! message could not be sent.";
    }
    } else {
    http_response_code(400);
    echo 'You are a spammer!';
    }
    

    That’s it, your PHP AJAX based contact form is ready to execute.

  Check out the Demo 

 

[purchase_link id=”606″ text=”Add to Cart” style=”button” color=”green”]

Article by Shrinivas Naik

Hi, This is Shrinivas I am a web developer and WordPress enthusiast. I am also a hobby blogger who loves to write about WordPress, web tools, blogging and technology.


2 comments on “How to Create PHP AJAX Contact Form with Google reCaptcha
  1. Oh, Thank God! I have spent two days testing scripts for a contact form on a one-page parallax website that has A LOT of javascript. Because of this every script I tried was conflicting with something. The site is so beautiful that I didn’t want to have to redesign the site just to get a captcha contact form to work! So I paid the $5 for this script and WAALAA! It works perfect! All I have to do is tweak a little CSS and the site will be live.

    Thank you very much for creating this script and offering it here!

Leave a Reply


This function has been disabled for TechSini