Integrate Google reCAPTCHA in Modal Popup Form with Ajax using PHP

Google reCAPTCHA is designed to protect websites from spam and abuse. It helps to integrate CAPTCHA functionality into the web page without any hassle. You can add Google reCAPTCHA in HTML form and verify the submission using PHP. With the reCAPTCHA widget, the user needs to select the checkbox to verify as a human. The reCAPTCHA checkbox is the best replacement for the generic CAPTCHA code verification that provides a user-friendly way for spam protection.

The Google reCAPTCHA can be implemented in the popup box or modal window. You can add reCAPTCHA widget to the HTML form embedded in a dialog box and validate the response with Ajax. In this tutorial, we will show you how to integrate Google reCAPTCHA in modal popup form with Ajax and PHP.

In the example Google reCAPTCHA Ajax Form script, we will add reCAPTCHA checkbox widget to the contact form in the popup box and validate the response with Ajax submission using PHP.

  • Build a modal component and add an HTML form element in the lightbox popup.
  • Add reCAPTCHA widget in popup HTML form.
  • Submit form data and reCAPTCHA response with jQuery Ajax for server-side processing.
  • Validate request by verifying the user’s response with Google reCAPTCHA API.
  • Retrieve form data and send contact request info via email using PHP.

Generate reCAPTCHA API Keys

Before getting started, you need to register the domain of your website and generate reCAPTCHA API keys.

Register a new site:
Go to the Google reCAPTCHA Admin console and register domain.

  • Label – Make it easier for you to identify the site in the future.
  • reCAPTCHA type – Select Challenge (v2) » “I’m not a robot” Checkbox
  • Domains – Specify the domain of the website.
google-recaptcha-checkbox-admin-register-site-domain-codexworld

Click SUBMIT to proceed.

Get Site Key and Secret Key:
After the submission, your site will be registered with reCAPTCHA v2 and the API keys will be generated. The Site Key and Secret Key need to be specified in the script at the time of calling Google reCAPTCHA API.

  • Site Key – This key is used in the client-side HTML code.
  • Secret Key – This key helps to authorize communication between your site and the reCAPTCHA server and is used in the server-side script for the user’s response verification.
google-recaptcha-v3-api-keys-create-site-secret-key-codexworld

Copy the Site Key and Secret Key for later use in the Google reCAPTCHA v2 API integration code.

Create Contact Form in Popup Box

At first, we need to create a modal component to build a popup box and embed an HTML form on it. In this example, we will use Bootstrap’s modal component for the popup window.

1. Include jQuery library.

<script src="js/jquery.min.js"></script>

2. Include the CSS and JS library files of Bootstrap.

<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/bootstrap.min.js"></script>

3. Create a button element that will trigger the modal popup.

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
    Launch Contact Modal
</button>

4. Define HTML elements to build a modal window.

  • Add form and input elements to the popup box.
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">Contact Us</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="contactForm">
            <div class="modal-body">
                <div class="frm-status"></div>
                <div class="mb-3">
                    <label class="form-label">Name</label>
                    <input type="text" class="form-control" name="name" placeholder="Enter your name" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Email</label>
                    <input type="email" class="form-control" name="email" placeholder="Enter email address" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Message</label>
                    <textarea class="form-control" name="message" rows="3" placeholder="Your message here..." required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
            </form>
        </div>
    </div>
</div>

Add reCAPTCHA Widget in Popup Form

In the previous step, we created a modal popup component and added the form elements in the popup. Now, we will add the reCAPTCHA widget in the popup form.

1. Load the reCAPTCHA JavaScript API library before the HTML form popup element.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

2. Add g-recaptcha tag under the popup form where you want to display the reCAPTCHA checkbox widget.

  • This tag should be a DIV element with class name g-recaptcha.
  • The Site Key of the reCAPTCHA API needs to be specified in the data-sitekey attribute.
<div class="mb-3">
    <!-- reCAPTCHA widget -->
    <div class="g-recaptcha" data-sitekey="Your_reCAPTCHA_Site_Key"></div>
</div>

Popup Form Submission via Ajax using jQuery

We will use the Ajax method to submit the form data and reCAPTCHA response to the server-side script (form_submit.php).

  • Use jQuery ajax() method to post form data via Ajax HTTP request.
  • Select values from all input elements including reCAPTCHA response using jQuery serialize() method.
  • Once the request is processed by the server-side script and the response comes, reset the form and reinitialize the reCAPTCHA widget.
  • Display Captcha verification status in popup form.
<script>
// Form submit handler
document.querySelector("#contactForm").addEventListener("submit", function(e){
    e.preventDefault();
    
    // Post form data via ajax request
    $.ajax({
        type:'POST',
        url:'form_submit.php',
        dataType: "json",
        data: $('#contactForm').serialize()+'&submit=1',
        beforeSend: function () {
            $(":input").prop("disabled", true);
            $(':button[type="submit"]').prop("disabled", true);
            $(':button[type="submit"]').text('Submitting...');
        },
        success:function(data){
            if(data.status == 1){
                $('#contactForm')[0].reset();
                $('.frm-status').html('<div class="alert alert-success">'+data.msg+'</div>');
            }else{
                $('.frm-status').html('<div class="alert alert-danger">'+data.msg+'</div>');
            }

            $(':button[type="submit"]').prop("disabled", false);
            $(':button[type="submit"]').text('Submit');
            $(":input").prop("disabled", false);

            // Reinitialize recaptcha widget
            grecaptcha.reset();
        }
    });
});
</script>

Verify reCAPTCHA Response with PHP

In this server-side script (form_submit.php), we will verify the user’s response and process the contact request.

  • Validate form input fields to check whether the user fills in the correct values.
  • Use the g-recaptcha-response POST parameter to get the user’s response token from the client-side reCAPTCHA widget.
  • Execute a cURL request to verify the response token with reCAPTCHA API using PHP.
  • Pass the Site Secret Key (secret), response token (response), and user’s IP (remoteip) in POST parameters.
  • If the reCAPTCHA response is valid and successful, process the contact form submission request further (such as sending an email notification to the site admin).
  • Return the status response in JSON format.
<?php 
// Google reCAPTCHA API keys settings
$secretKey  'Your_reCaptcha_Secret_Key'

// Email settings 
$recipientEmail 'admin@example.com'

// If form data is submitted by AJAX request
if(isset($_POST['submit'])){
    
// Define default response
    
$response = array(
        
'status' => 0,
        
'msg' => 'Something went wrong, please try again after some time.'
    
);
    
    
// Retrieve value from the form input fields 
    
$name trim($_POST['name']); 
    
$email trim($_POST['email']); 
    
$message trim($_POST['message']); 
    
    
$valErr '';
    if(empty(
$name)){
        
$valErr .= 'Please enter your name.<br/>';
    }
    if(empty(
$email) || !filter_var($emailFILTER_VALIDATE_EMAIL)){
        
$valErr .= 'Please enter a valid email.<br/>';
    }
    if(empty(
$message)){
        
$valErr .= 'Please enter your message.<br/>';
    }

    if(empty(
$valErr)){
        
// Validate reCAPTCHA response 
        
if(!empty($_POST['g-recaptcha-response'])){ 
            
// Google reCAPTCHA verification API Request 
            
$api_url 'https://www.google.com/recaptcha/api/siteverify'
            
$resq_data = array( 
                
'secret' => $secretKey
                
'response' => $_POST['g-recaptcha-response'], 
                
'remoteip' => $_SERVER['REMOTE_ADDR']
            ); 
            
            
// Initialize cURL request
            
$curlConfig = array( 
                
CURLOPT_URL => $api_url
                
CURLOPT_POST => true
                
CURLOPT_RETURNTRANSFER => true
                
CURLOPT_POSTFIELDS => $resq_data
                
CURLOPT_SSL_VERIFYPEER => false 
            
); 
 
            
$ch curl_init(); 
            
curl_setopt_array($ch$curlConfig); 
            
$response curl_exec($ch); 
            if (
curl_errno($ch)) { 
                
$api_error curl_error($ch); 
            } 
            
curl_close($ch); 
 
            
// Decode JSON data of API response in array 
            
$responseData json_decode($response); 
 
            
// If the reCAPTCHA API response is valid 
            
if(!empty($responseData) && $responseData->success){ 
                
// Send email notification to the site admin 
                
$to $recipientEmail
                
$subject 'New Contact Request Submitted'
                
$htmlContent 
                    <h4>Contact request details</h4> 
                    <p><b>Name: </b>"
.$name."</p> 
                    <p><b>Email: </b>"
.$email."</p> 
                    <p><b>Message: </b>"
.$message."</p> 
                "

                 
                
// Always set content-type when sending HTML email 
                
$headers "MIME-Version: 1.0" "\r\n"
                
$headers .= "Content-type:text/html;charset=UTF-8" "\r\n"
                
// Sender info header 
                
$headers .= 'From:'.$name.' <'.$email.'>' "\r\n"
                 
                
// Send email 
                
@mail($to$subject$htmlContent$headers); 

                
$response = array(
                    
'status' => 1,
                    
'msg' => 'Thank you! Your contact request has been submitted successfully.'
                
);
            }else{
                
$response['msg'] = !empty($api_error)?$api_error:'The reCAPTCHA verification failed, please try again.';
            }
        }else{
            
$response['msg'] = 'Please check the reCAPTCHA checkbox.';
        }
    }else{
        
$valErr = !empty($valErr)?'<br/>'.trim($valErr'<br/>'):''
        
$response['msg'] = 'Please fill all the mandatory fields:'.$valErr;
    }
    
    
// Return response
    
echo json_encode($response);
}
?>

Integrate Google reCAPTCHA v3 in HTML Form with PHP

Conclusion

The popup element is very useful to display multiple sections in a single web page. Using Bootstrap’s JavaScript modal plugin, you can add a dialog window to the web page with HTML and CSS. This example code helps you to protect the form on the popup using the reCAPTCHA checkbox in HTML. Here we have used contact form elements, but you can add any type of form (login, registration, etc.) to popup and integrate Google reCAPTCHA protection to Ajax form in popup box.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up