Secure Your PHP Forms with Google reCAPTCHA v3 Using jQuery AJAX

Learn how to build a secure AJAX form using Core PHP with Google reCAPTCHA v3 and MySQL. Includes client-side and server-side validation, secure database insertion, and real-time feedback.

Secure Your PHP Forms with Google reCAPTCHA v3 Using jQuery AJAX Image

Introduction

In modern web applications, preventing spam and securing forms is critical. In this tutorial, you’ll learn how to submit a form using jQuery AJAX in Core PHP, validate it on both the client and server side, and secure it using Google reCAPTCHA v3. All data will be stored securely in a MySQL database.

Prerequisites:

Before starting, make sure you have:

Database Setup

First, create a MySQL table to store the form submissions:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Frontend: index.php

This file contains the form, jQuery AJAX, and Google reCAPTCHA v3 integration.

<!DOCTYPE html>
<html>
<head>
    <title>AJAX Form with reCAPTCHA v3</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Add your actual site key -->
    <script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY"></script>
</head>
<body>

<h2>AJAX Form with reCAPTCHA v3</h2>

<div id="message"></div>

<form id="ajaxForm">
    <label>Name:</label><br>
    <input type="text" name="name" id="name"><br><br>

    <label>Email:</label><br>
    <input type="email" name="email" id="email"><br><br>

    <input type="hidden" name="recaptcha_token" id="recaptcha_token">
    <input type="submit" value="Submit">
</form>

<script>
$(document).ready(function () {
    $('#ajaxForm').on('submit', function (e) {
        e.preventDefault();

        grecaptcha.ready(function () {
        	<!-- Add your actual site key -->
            grecaptcha.execute('YOUR_SITE_KEY', { action: 'submit' }).then(function (token) {
                $('#recaptcha_token').val(token);

                $.ajax({
                    url: 'form.php',
                    method: 'POST',
                    data: $('#ajaxForm').serialize(),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#message').html('<p style="color:green;">' + response.message + '</p>');
                            $('#ajaxForm')[0].reset();
                        } else {
                            let errorList = response.errors.map(err => `<li>${err}</li>`).join('');
                            $('#message').html('<ul style="color:red;">' + errorList + '</ul>');
                        }
                    },
                    error: function () {
                        $('#message').html('<p style="color:red;">An unexpected error occurred.</p>');
                    }
                });
            });
        });
    });
});
</script>

</body>
</html>

Don’t forget to replace YOUR_SITE_KEY with your real site key.

Backend: form.php

Handles reCAPTCHA validation, server-side validation, and secure data insertion with prepared statements.

<?php
header('Content-Type: application/json');

$errors = [];
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$recaptcha_token = $_POST['recaptcha_token'] ?? '';

// Validate fields
if (empty($name)) $errors[] = "Name is required.";
if (empty($email)) {
    $errors[] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email format.";
}
if (empty($recaptcha_token)) $errors[] = "reCAPTCHA verification failed.";

// Verify reCAPTCHA
if (empty($errors)) {
    $secret = 'YOUR_SECRET_KEY';
    $verify = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$recaptcha_token}");
    $captcha_response = json_decode($verify);

    if (!$captcha_response->success || $captcha_response->score < 0.5) {
        $errors[] = "Failed reCAPTCHA verification.";
    }
}

// Insert into DB
if (empty($errors)) {
    $conn = new mysqli("localhost", "root", "", "test_db");
    if ($conn->connect_error) {
        echo json_encode(['success' => false, 'errors' => ['DB connection failed.']]);
        exit;
    }

    $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $email);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Form submitted successfully!']);
    } else {
        echo json_encode(['success' => false, 'errors' => ['Failed to save data.']]);
    }

    $stmt->close();
    $conn->close();
} else {
    echo json_encode(['success' => false, 'errors' => $errors]);
}

Replace YOUR_SECRET_KEY with your actual reCAPTCHA secret key.

Advantages of This Setup

  • No page reload (better UX)
  • Spam protection with reCAPTCHA v3
  • Secure insert using prepared statements
  • Friendly error and success messages
  • Works on shared hosting or local server

Bonus Tip

For local testing, ensure you register localhost in your reCAPTCHA admin console.

Conclusion

This tutorial demonstrated how to build a secure and interactive AJAX-based form in Core PHP, enhanced with Google reCAPTCHA v3 for spam protection. With proper validation and secure storage, this technique is ideal for contact forms, registrations, or feedback pages in any PHP project.

Happy Coding! 😊

Do you Like?