Easy jQuery AJAX PHP Captcha – 2 minute setup

By Sam Deering

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.


  • 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.


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




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




Uses Bootstrap markup.

refresh captcha


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.


    //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"]');



        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()

               onkeyup: false,
               rules: {
                    "firstname": {
                        "required": true
                    "lastname": {
                        "required": true
                    "email": {
                        "required": true
                    "captcha": {
                        "required": true,
                        "remote" :
                          url: '/php/checkCaptcha.php',
                          type: "post",
                              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()


captcha correct, submit form success!

'); });, textStatus) { //fail console.log( "fail - an error occurred: (" + textStatus + ")." ); }); } }); } } WEBAPP.init(); });


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

$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
imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $_SESSION['captcha']);

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


checkCaptcha.php – this is simple. It checks the if the code matches and returns result to the front-end.

< ?php

    echo json_encode(strtolower($_REQUEST['code']) == strtolower($_SESSION['captcha']));
    echo 0; // no code

I hoped this helped you setup a quick captcha! If so, please leave a comment! :)

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • MarilynEtheridge

    My friend’s sister m­a­k­e­s­ $76/hr on the PC. She has been d­i­s­a­l­l­o­­w­e­d of labor designed for 7 months but last few month her take-home pay was $14998 honorable working on the PC designed for a a small number of hours. He supposed BIG44.­c­o­m

  • Raphael

    Thank you for your form. I like the form on the Repo better. It uses cool image recognition.

  • Wnw Slutnz

    how we can embed more than 1 captcha in one page
    i am facing problem

  • ammar

    i have downloded the folder but capcha is not refreshing and also form is not submitting

    plz help

    • nirdosh shrestha

      m not sure about refresh but form is not submitting because in main.js you did not give the correct path in line no 66 and 96

  • openairhoster

    So how do I catch the input variables from the the form ? I tried to use $_REQUEST[firstname] or $_POST[firstname] in dummyScript.php but that didn’t have any effect …

    • ChingonDelNorte

      Yes, I’ve the same question, I tried $_GET[firstname] as well and it didn’t work either.

      • otto

        How can I collect the data ? Thanks

        • Van Fanel

          I use this:


          on app/main.js to send the form. hope this help.

  • nirdosh shrestha

    is this plugin working ? how to submit form ? it work in live but not in local. please try to reply so plugin make worth

  • Cornélio José Wiedemann

    o loco tio
    mt bom mesmo isu
    valeu ai safadao

  • Verena Michels

    How to catch the input variables:

    parse_str($_POST[data], $form);

    Thanks for the form.

  • parimal

    not working ..

  • Mike Petrosyan

    Hi. How can I change submit button?

  • Vittal

    Really awesome it worked me exactly what i need, thanks a lot Sam Deering

  • Gerd

    the script works on my development server but not on the production server. After click on Submit the validation works but the submit of data doesn’t work.

  • Gerd

    I thought as it is jquery It would’nt matter which server I use. Any idea yo solve the problem?

  • Rob

    No idea where to put the jquery code

  • Bala Murugan

    the captcha is not showing…This error is display in network

    Provisional headers are shown

Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.