AJAX Form Submission with Google reCAPTCHA v2 in PHP

Last updated 2 weeks, 3 days ago | 29 views 75     5

Tags:- PHP Ajax CAPTCHA

Second page link: Secure Your Forms with Google reCAPTCHA v2 in PHP: Step-by-Step Guide

Perfect! Here's a complete guide on integrating Google reCAPTCHA v2 with AJAX-based form submission in PHP — for better user experience and secure form handling.


⚙️ AJAX Form Submission with Google reCAPTCHA v2 in PHP

AJAX-powered forms are sleek and user-friendly — no page reloads, smooth interactions. But to maintain security, especially against spam and bots, it's crucial to integrate Google reCAPTCHA even in asynchronous forms.

This tutorial walks you through:

  • Setting up a reCAPTCHA-enabled form

  • Validating it server-side with PHP

  • Submitting data with AJAX

  • Handling response feedback


Folder Structure

/recaptcha-ajax-form/
├── index.html         <-- HTML form + AJAX
├── submit.php         <-- Form handler + reCAPTCHA validation

Step 1: Get reCAPTCHA Keys

  1. Visit: https://www.google.com/recaptcha/admin

  2. Choose reCAPTCHA v2 – "I'm not a robot" checkbox

  3. Register your domain (or localhost)

  4. Copy the Site Key and Secret Key


Step 2: HTML Form + AJAX – index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AJAX Form with reCAPTCHA</title>
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  <style>
    #response { margin-top: 15px; font-weight: bold; }
  </style>
</head>
<body>
  <h2>Contact Us</h2>
  <form id="contactForm">
    <label>Name:</label><br>
    <input type="text" name="name" required><br><br>

    <label>Message:</label><br>
    <textarea name="message" required></textarea><br><br>

    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_HERE"></div><br>

    <button type="submit">Submit</button>
  </form>

  <div id="response"></div>

  <script>
    document.getElementById("contactForm").addEventListener("submit", function(e) {
      e.preventDefault(); // Prevent default form submission

      const form = e.target;
      const formData = new FormData(form);

      const recaptchaResponse = grecaptcha.getResponse();
      if (!recaptchaResponse) {
        document.getElementById("response").innerHTML = "Please complete the CAPTCHA.";
        return;
      }

      formData.append('g-recaptcha-response', recaptchaResponse);

      fetch("submit.php", {
        method: "POST",
        body: formData
      })
      .then(res => res.text())
      .then(data => {
        document.getElementById("response").innerHTML = data;
        grecaptcha.reset(); // reset CAPTCHA after each submission
        form.reset(); // optional: reset form fields
      })
      .catch(err => {
        document.getElementById("response").innerHTML = "Error submitting form.";
        console.error(err);
      });
    });
  </script>
</body>
</html>

Replace YOUR_SITE_KEY_HERE with your actual site key from Google.


Step 3: Server-Side Handler – submit.php

<?php
// Secret key from Google
$secret = "YOUR_SECRET_KEY_HERE";

// Validate reCAPTCHA
$captcha = $_POST['g-recaptcha-response'] ?? '';

if (!$captcha) {
    echo "<span style='color:red;'>CAPTCHA is missing. Please try again.</span>";
    exit;
}

$verify = file_get_contents(
    "https://www.google.com/recaptcha/api/siteverify?secret=" . urlencode($secret) . "&response=" . urlencode($captcha)
);
$response = json_decode($verify);

if (!$response->success) {
    echo "<span style='color:red;'>CAPTCHA verification failed. Try again.</span>";
    exit;
}

// Validate other form data
$name = trim($_POST['name'] ?? '');
$message = trim($_POST['message'] ?? '');

if ($name === '' || $message === '') {
    echo "<span style='color:red;'>Please fill in all fields.</span>";
    exit;
}

// [Optionally: Save to database or send email here]

echo "<span style='color:green;'>Thank you, $name. Your message has been received!</span>";
?>

Replace YOUR_SECRET_KEY_HERE with your secret key from Google.


Flow Summary

  1. User fills in the form and completes the CAPTCHA

  2. JavaScript submits the form data + reCAPTCHA token via AJAX

  3. PHP validates the reCAPTCHA token via Google’s API

  4. PHP processes and sends a text response (which AJAX displays)


Tips

  • Use HTTPS — required for reCAPTCHA to work properly

  • Call grecaptcha.reset() to allow resubmission after a failed attempt

  • Sanitize inputs before processing

  • Consider rate limiting or IP logging for added protection


⚠️ Common Pitfalls

Issue Fix
CAPTCHA doesn’t show Double check your site key and domain match
CAPTCHA doesn’t validate Ensure g-recaptcha-response is sent with the request
PHP errors not showing Enable error reporting in development (error_reporting(E_ALL);)
JS says “undefined error” Check for network errors or CORS issues in browser console

✅ That's It!

You've now built a fully secure, CAPTCHA-protected AJAX form using Google reCAPTCHA v2 and PHP. This setup is clean, user-friendly, and effective against spam bots.