Easy jQuery AJAX PHP Captcha – 2 minute setup

Share this article

Setup a working AJAX Captcha in minutes.
This is for when you need a super quick Captcha for a form with no pain of unreadable reCaptcha’s or such. It’s NOT a super hard to guess Captcha system it just provides a very basic captcha which is generated by PHP. Using this method does however allow you to choose your own size, font, color, background color which is nice. I have also integrated it with jQuery Validate plugin with a remote ajax request to check if the captcha is correct.

Features

  • Integrated with jQuery Validate plugin.
  • Custom captcha font, sizes, colors, background colors.
  • Uniquely generated back-end by PHP.
  • No reCaptcha pain, setup in seconds, no API key required.

Demo

The demo is built upon a lightweight bootstrap I created using jQuery, jQuery.validate, Require.js, Backbone.js, Bootstrap.

CAPTCHA DEMO easy-jquery-php-captcha

Download

There is a complete working download package on GitHub. Star and Fork as you please. :)

VIEW ON GITHUB

Setup

HTML

Uses Bootstrap markup.

<label class="" for="captcha">*Please enter the verication code shown below.</label>
<div id="captcha-wrap">
    <img src="/img/refresh.jpg" alt="refresh captcha" id="refresh-captcha" /> <img src="/php/newCaptcha.php" alt="" id="captcha" />
</div>
<input class="narrow text input" id="captcha" name="captcha" type="text" placeholder="Verification Code"/>

jQuery

Validation is run from a WEBAPP object which caches DOM elements and sets up the events for captcha refresh. I have used the Remote Validation Rule to check if the captcha is correct using ajax.

$(function()
{

    //jQuery Captcha Validation
    WEBAPP = {

        settings: {},
        cache: {},

        init: function() {

            //DOM cache
            this.cache.$form = $('#captcha-form');
            this.cache.$refreshCaptcha = $('#refresh-captcha');
            this.cache.$captchaImg = $('img#captcha');
            this.cache.$captchaInput = $(':input[name="captcha"]');

            this.eventHandlers();
            this.setupValidation();

        },

        eventHandlers: function() {

            //generate new captcha
            WEBAPP.cache.$refreshCaptcha.on('click', function(e)
            {
                WEBAPP.cache.$captchaImg.attr("src","/php/newCaptcha.php?rnd=" + Math.random());
            });
        },

        setupValidation: function()
        {

            WEBAPP.cache.$form.validate({
               onkeyup: false,
               rules: {
                    "firstname": {
                        "required": true
                    },
                    "lastname": {
                        "required": true
                    },
                    "email": {
                        "required": true
                    },
                    "captcha": {
                        "required": true,
                        "remote" :
                        {
                          url: '/php/checkCaptcha.php',
                          type: "post",
                          data:
                          {
                              code: function()
                              {
                                  return WEBAPP.cache.$captchaInput.val();
                              }
                          }
                        }
                    }
                },
                messages: {
                    "firstname": "Please enter your first name.",
                    "lastname": "Please enter your last name.",
                    "email": {
                        "required": "Please enter your email address.",
                        "email": "Please enter a valid email address."
                    },
                    "captcha": {
                        "required": "Please enter the verifcation code.",
                        "remote": "Verication code incorrect, please try again."
                    }
                },
                submitHandler: function(form)
                {
                    /* -------- AJAX SUBMIT ----------------------------------------------------- */

                    var submitRequest = $.ajax({
                         type: "POST",
                         url: "/php/dummyScript.php",
                         data: {
                            "data": WEBAPP.cache.$form.serialize()
                        }
                    });

                    submitRequest.done(function(msg)
                    {
                        //success
                        console.log('success');
                        $('body').html('<h1>captcha correct, submit form success!</h1>');
                    });

                    submitRequest.fail(function(jqXHR, textStatus)
                    {
                        //fail
                        console.log( "fail - an error occurred: (" + textStatus + ")." );
                    });

                }

            });

        }

    }

    WEBAPP.init();

});

PHP

newCaptcha.php file simply creates a new captcha image based on the font provided and color settings. It stores the captcha code in a PHP session variable called captcha.
< ?php
session_start();

$string = '';
for ($i = 0; $i < 5; $i++) {
    $string .= chr(rand(97, 122));
}

$_SESSION['captcha'] = $string; //store the captcha

$dir = '../fonts/';
$image = imagecreatetruecolor(165, 50); //custom image size
$font = "PlAGuEdEaTH.ttf"; // custom font style
$color = imagecolorallocate($image, 113, 193, 217); // custom color
$white = imagecolorallocate($image, 255, 255, 255); // custom background color
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $_SESSION['captcha']);

header("Content-type: image/png");
imagepng($image);

?>
checkCaptcha.php – this is simple. It checks the if the code matches and returns result to the front-end.
< ?php
session_start();

if(isset($_REQUEST['code']))
{
    echo json_encode(strtolower($_REQUEST['code']) == strtolower($_SESSION['captcha']));
}
else
{
    echo 0; // no code
}
?>
I hoped this helped you setup a quick captcha! If so, please leave a comment! :)

Frequently Asked Questions (FAQs) about jQuery PHP Captcha

How can I integrate jQuery PHP Captcha into my existing form?

Integrating jQuery PHP Captcha into your existing form is a straightforward process. First, you need to include the jQuery library and the captcha script in your HTML file. Then, you need to add a captcha field in your form. This field will be automatically filled by the captcha script. Finally, you need to validate the captcha response on the server side using PHP. This involves sending a request to the captcha server and checking the response. If the response is valid, you can proceed with the form submission.

What are the benefits of using jQuery PHP Captcha?

jQuery PHP Captcha offers several benefits. It provides an additional layer of security to your forms, preventing automated bots from submitting spam. It’s also easy to integrate into your existing forms and doesn’t require any additional dependencies. Moreover, it’s highly customizable, allowing you to adjust its appearance and behavior to fit your needs.

Can I customize the appearance of jQuery PHP Captcha?

Yes, you can customize the appearance of jQuery PHP Captcha. The captcha script provides several options for customization, including the color, size, and font of the captcha text. You can also choose whether to display the captcha as an image or as plain text. To customize the captcha, you need to modify the options in the captcha script.

How can I handle errors in jQuery PHP Captcha?

Handling errors in jQuery PHP Captcha involves checking the response from the captcha server. If the response is invalid, you can display an error message to the user. This can be done using jQuery’s error handling functions. You can also log the error on the server side for debugging purposes.

Is jQuery PHP Captcha compatible with all browsers?

jQuery PHP Captcha is compatible with all modern browsers that support JavaScript. This includes Chrome, Firefox, Safari, and Edge. However, it may not work correctly in older browsers that do not support JavaScript or have JavaScript disabled.

How can I refresh the captcha image in jQuery PHP Captcha?

To refresh the captcha image in jQuery PHP Captcha, you can use the refresh function provided by the captcha script. This function generates a new captcha image and updates the captcha field in your form.

Can I use jQuery PHP Captcha without jQuery?

jQuery PHP Captcha relies on jQuery for its functionality, so it cannot be used without jQuery. However, you can use other captcha solutions that do not require jQuery if you prefer not to use jQuery in your project.

How secure is jQuery PHP Captcha?

jQuery PHP Captcha provides a reasonable level of security against automated spam submissions. However, like all captcha solutions, it is not foolproof and should be used in conjunction with other security measures, such as form validation and server-side filtering.

Can I use jQuery PHP Captcha in a multi-page form?

Yes, you can use jQuery PHP Captcha in a multi-page form. The captcha field can be included in each page of the form, and the captcha response can be validated on the server side when the form is submitted.

How can I troubleshoot issues with jQuery PHP Captcha?

Troubleshooting issues with jQuery PHP Captcha involves checking the console for errors, verifying that the captcha script is correctly included in your HTML file, and ensuring that the captcha field is correctly added to your form. If you’re still having issues, you can seek help from the community or contact the captcha script’s author for support.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week