How To Add BotDetect CAPTCHA Protection to jQuery Application

Unlike Recaptcha the Stalker -- BotDetect CAPTCHA works in China! Licensable source-code; self-hosted -- doesn't stalk -- nor does it slurp your form-data! Think: GDPR & LGPD!

jQuery application CAPTCHA Integration Steps

Integration in jQuery app -- Introduction

BotDetect Captcha protection can be added to your jQuery applications using the BotDetect CAPTCHA jQuery Plugin. Displaying the Captcha challenge can be as simple as:

<div id="botdetect-captcha" data-stylename="exampleCaptcha"></div> 

and using validateUnsafe(callback) method to validate Captcha code on form submit:

// On form submit 
$('#exampleForm').submit(function(event) { 

  captcha.validateUnsafe(function(isCaptchaCodeCorrect) { 

    if (isCaptchaCodeCorrect) { 
      // Captcha code is correct 
    } else { 
      // Captcha code is incorrect 
    } 
    
  }); 

  event.preventDefault(); 
}); 

PLEASE NOTE: Since Captcha protects some server-side action, a Captcha code needs to be validated again on the server-side -- in your backend tech specific way -- before that protected action is executed.

You can see how BotDetect Captcha protection is added to a simple HTML form by running the BotDetect Captcha integration code examples coming with the each BotDetect product's free download package.

..............................................................

jQuery application with ASP.NET backend

  1. Install BotDetect CAPTCHA jQuery Plugin
  2. Display BotDetect CAPTCHA in HTML template
  3. Captcha Validation
  4. ASP.NET server-side Configuration

Install BotDetect CAPTCHA jQuery Plugin

Step 1: Install BotDetect Captcha jQuery Plugin

Step 2: Include BotDetect Captcha jQuery Plugin in your web app

<script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 

Step 3: Load BotDetect Captcha jQuery Plugin in your application

The following step ensures that BotDetect CAPTCHA library works properly in your jQuery application. Please follow it carefully.

$(document).ready(function() { 
    // DOM ready 

    var captcha = $('#botdetect-captcha').captcha({ 
      captchaEndpoint: 'captcha-endpoint/BotDetectCaptcha.ashx' 
    }); 

}); 

When DOM is loaded, we load jQuery Captcha plugin using the .captcha() method -- passing the captchaEndpoint setting which represents the path where BotDetect ASP.NET Captcha responds. The captcha JavaScript object exposes all Captcha workflow functions and vars that we will use later during the form submission part of the workflow.

Before you set the path to captchaEndpoint setting, we need to clarify what we set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect ASP.NET Captcha library. If you deployed BotDetect ASP.NET Captcha library in the root of your domain, then you don't need to set this path.
  • /BotDetectCaptcha.ashx: is SimpleCaptchaHandler path, which is described on Register BotDetect HttpHandler for CAPTCHA Requests guide below.

To ensure that you have set a right path to captchaEndpoint setting, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/BotDetectCaptcha.ashx (replace the exact path of your domain). If this results with an error message ("unknown command") then you set the right path, since that is the BotDetect Captcha who responded error (when you fail to set correct path, then your server will respond with 404 instead). Please note, in order to perform this check, BotDetect Captcha Generator needs to be installed & deployed to your server.

Display BotDetect CAPTCHA In Your HTML Template

Displaying the Captcha challenge can be as simple as:

<div id="botdetect-captcha" data-stylename="exampleCaptcha"></div> 

You simply declare a HTML element and assign data-stylename attribute a captcha style name defined in botdetect.xml configuration file.

The captcha html markup will be displayed as soon as you load the jQuery Captcha plugin in your application as described in the Step 3 above.

Captcha Validation

Client-side Captcha validation in your jQuery application

BotDetect Captcha jQuery Plugin provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
// On form submit 
$('#exampleForm').submit(function(event) { 

  captcha.validateUnsafe(function(isCaptchaCodeCorrect) { 

    if (isCaptchaCodeCorrect) { 
      // Captcha code is correct 
    } else { 
      // Captcha code is incorrect 
    } 
    
  }); 

  event.preventDefault(); 
}); 

OR:

  • Using data-correct-captcha directive attribute to validate Captcha code on blur event:

You need to add the data-correct-captcha attribute in the captcha code input element. BotDetect Captcha jQuery will then automatically validate captcha code on blur event.

<input 
  type="text" 
  name="captchaCode" 
  id="captchaCode" 
  data-correct-captcha 
> 

And you can check the captcha validation result by listing the custom validatecaptcha event as the code shown below.

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) { 
  if (isCorrect) { 
    // UI Captcha validation passed 
  } else { 
    // UI Captcha validation failed 
  } 
}) 

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

ASP.NET Server-side Captcha validation

$('#exampleForm').submit(function(event) { 
  
  // captcha id for validating captcha at server-side 
  var captchaId = captcha.getCaptchaId(); 

  // captcha code input value for validating captcha at server-side 
  var captchaCode = $('#captchaCode').val(); 

  var postData = { 
    captchaId: captchaId, 
    captchaCode: captchaCode 
  }; 

  $.ajax({ 
    method: 'POST', 
    url: '/your-server-side-api-url', 
    dataType: 'json', 
    contentType: 'application/json', 
    data: JSON.stringify(postData), 
    success: function(response) { 
      if (response.success) { 
        // captcha validation passed at server-side 
      } else { 
        // captcha validation failed at server-side 
      } 
    }, 
    complete: function() { 
      // we should reload captcha image after server-side validation is completed 
      // in order to update new captcha code for current captcha id 
      captcha.reloadImage(); 
    } 
  }); 
 
}); 

To validate Captcha at server-side, we need to send captchaId property of captcha JavaScript object and captcha code visitor submited to server-side.

Once request finished, we always reload Captcha by calling the reloadImage() function of captcha JavaScript object. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using Validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • ASP.NET Web API 2 Captcha validation:
using BotDetect.Web; 
using Newtonsoft.Json; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Text; 
using System.Web.Http; 

namespace ProductApp.Controllers 
{ 
    public class ExampleController : ApiController 
    { 
        // POST api/example 
        public HttpResponseMessage Post([FromBody]Models.BasicForm value) 
        { 
            // validate captcha 
            SimpleCaptcha captcha = new SimpleCaptcha(); 
            bool isHuman = captcha.Validate(value.CaptchaCode, value.CaptchaId); 

            if (isHuman) 
            { 
                // Captcha validation passed 
                // TODO: do whatever you want here 
            } 

            // the object that stores validation result 
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>(); 
            validationResult.Add("success", isHuman); 

            // write the validation result as json string for sending it back to client 
            string jsonString = JsonConvert.SerializeObject(validationResult); 
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); 
            response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); 

            return response; 
        } 
    } 
} 
  • ASP.NET Generic Handler Captcha validation:
<%@ WebHandler Language="C#" Class="BasicHandler" %> 
using System; 
using System.Web; 
using System.IO; 
using Newtonsoft.Json; 
using System.Collections.Generic; 
using BotDetect.Web; 

public class BasicHandler : IHttpHandler 
{ 
    public void ProcessRequest (HttpContext context) 
    { 
        if (HttpContext.Current.Request.HttpMethod == "POST") 
        { 
            string dataJson = new StreamReader(context.Request.InputStream).ReadToEnd(); 

            Dictionary<string, string> formDataObj = new Dictionary<string, string>(); 
            formDataObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataJson); 

            string captchaId = formDataObj["captchaId"]; 
            string captchaCode = formDataObj["captchaCode"]; 

            // validate captcha 
            SimpleCaptcha captcha = new SimpleCaptcha(); 
            bool isHuman = captcha.Validate(captchaCode, captchaId); 

            if (isHuman) 
            { 
                // Captcha validation passed 
                // TODO: do whatever you want here 
            } 

            // the object that stores validation result 
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>(); 
            validationResult.Add("success", isHuman); 

            // write the validation result as json string for sending it back to client 
            context.Response.ContentType = "application/json; charset=utf-8"; 
            context.Response.Write(JsonConvert.SerializeObject(validationResult)); 
        } 
    } 
} 

Display Captcha error message in your HTML template

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) { 
  if (!isCorrect) { 
    $('#message').text('Incorrect captcha code') 
  } 
}); 

To display captcha error message, simply listen the custom validatecaptcha event, which will be fired on captcha code input element's blur event and check the second argument (i.e isCorrect in the code above) of the callback function. If it returns false, this means that UI captcha validation failed.

ASP.NET server-side Configuration

Install BotDetect ASP.NET Captcha library on Server-side

Before integrating BotDetect Captcha in your jQuery application, you need to ensure you have installed BotDetect ASP.NET Captcha library on your server where your jQuery application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?xml version="1.0" encoding="UTF-8"?> 
<botdetect xmlns="https://captcha.com/schema/net" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="https://captcha.com/schema/net  
      https://captcha.com/schema/net/botdetect-4.4.0.xsd"> 

  <captchaStyles> 
    
    <captchaStyle> 
      <name>exampleCaptcha</name> 
      <userInputID>captchaCode</userInputID> 
      <codeLength>6</codeLength> 
    </captchaStyle> 

    <captchaStyle> 
      <name>loginCaptcha</name> 
      <userInputID>captchaCode</userInputID> 
      <codeLength>4-6</codeLength> 
      <codeStyle>Alphanumeric</codeStyle> 
    </captchaStyle> 

  </captchaStyles> 

</botdetect> 

To configure captcha options, you need to create botdetect.xml configuration file (with xml content like the one above this) in root folder of your project. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

..............................................................

jQuery application with JAVA backend

  1. Install BotDetect CAPTCHA jQuery Plugin
  2. Display BotDetect CAPTCHA in HTML template
  3. Captcha Validation
  4. Java server-side Configuration

Install BotDetect CAPTCHA jQuery Plugin

Step 1: Install BotDetect Captcha jQuery Plugin

Step 2: Include BotDetect Captcha jQuery Plugin in your web app

<script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 

Step 3: Load BotDetect Captcha jQuery Plugin in your application

The following step ensures that BotDetect CAPTCHA library works properly in your jQuery application. Please follow it carefully.

$(document).ready(function() { 
    // DOM ready 

    var captcha = $('#botdetect-captcha').captcha({ 
      captchaEndpoint: 'captcha-endpoint/botdetectcaptcha' 
    }); 

}); 

When DOM is loaded, we load jQuery Captcha plugin using the .captcha() method -- passing the captchaEndpoint setting which represents the path where BotDetect Java Captcha responds. The captcha JavaScript object exposes all Captcha workflow functions and vars that we will use later during the form submission part of the workflow.

Before you set the path to captchaEndpoint setting, we need to clarify what we set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect Java Captcha library. If you deployed BotDetect Java Captcha library in the root of your domain, then you don't need to set this path.
  • /botdetectcaptcha: is SimpleCaptchaServlet path, which is described on Register SimpleCaptchaServlet guide below.

To ensure that you set the captchaEndpoint to right path, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/botdetectcaptcha (replace the 'yourdomain.com' with your domain). If opening the url in browser results with an error message ('unknown command') then you set the right path since it is the BotDetect Captcha that responded with 'unknown command' error. Otherwise, if you failed to set right path, then your server will respond with 404 instead.

Please note, in order to perform this check, BotDetect Captcha Generator needs to be deployed to your server (described in II. Captcha Generator server-side configuration).

Display BotDetect CAPTCHA In Your HTML Template

Displaying the Captcha challenge can be as simple as:

<div id="botdetect-captcha" data-stylename="exampleCaptcha"></div> 

You simply declare a HTML element and assign data-stylename attribute a captcha style name defined in botdetect.xml configuration file.

The captcha html markup will be displayed as soon as you load the jQuery Captcha plugin in your application as described in the Step 3 above.

Captcha Validation

Client-side Captcha validation in your jQuery application

BotDetect Captcha jQuery Plugin provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
// On form submit 
$('#exampleForm').submit(function(event) { 

  captcha.validateUnsafe(function(isCaptchaCodeCorrect) { 

    if (isCaptchaCodeCorrect) { 
      // Captcha code is correct 
    } else { 
      // Captcha code is incorrect 
    } 
    
  }); 

  event.preventDefault(); 
}); 

OR:

  • Using data-correct-captcha directive attribute to validate Captcha code on blur event:

You need to add the data-correct-captcha attribute in the captcha code input element. BotDetect Captcha jQuery will then automatically validate captcha code on blur event.

<input 
  type="text" 
  name="captchaCode" 
  id="captchaCode" 
  data-correct-captcha 
> 

And you can check the captcha validation result by listing the custom validatecaptcha event as the code shown below.

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) { 
  if (isCorrect) { 
    // UI Captcha validation passed 
  } else { 
    // UI Captcha validation failed 
  } 
}) 

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

JAVA Server-side Captcha validation


$('#exampleForm').submit(function(event) { 
  
  // captcha id for validating captcha at server-side 
  var captchaId = captcha.getCaptchaId(); 

  // captcha code input value for validating captcha at server-side 
  var captchaCode = $('#captchaCode').val(); 

  var postData = { 
    captchaId: captchaId, 
    captchaCode: captchaCode 
  }; 

  $.ajax({ 
    method: 'POST', 
    url: '/your-server-side-api-url', 
    dataType: 'json', 
    contentType: 'application/json', 
    data: JSON.stringify(postData), 
    success: function(response) { 
      if (response.success) { 
        // captcha validation passed at server-side 
      } else { 
        // captcha validation failed at server-side 
      } 
    }, 
    complete: function() { 
      // we should reload captcha image after server-side validation is completed 
      // in order to update new captcha code for current captcha id 
      captcha.reloadImage(); 
    } 
  }); 
 
}); 

To validate Captcha at server-side, we need to send captchaId property of captcha JavaScript object and captcha code visitor submited to server-side.

Once request finished, we always reload Captcha by calling the reloadImage() function of captcha JavaScript object. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • Server-side Captcha validation in a Servlet is performed in the following way:
.... 

import com.captcha.botdetect.web.servlet.SimpleCaptcha; 

public class ExampleServlet extends HttpServlet { 

  @Override 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
   
    PrintWriter out = response.getWriter(); 
    Gson gson = new Gson(); 
    
    response.setContentType("application/json; charset=utf-8"); 
    
    JsonParser parser = new JsonParser(); 
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader()); 
    
    String captchaId = formDataObj.get("captchaId").getAsString(); 
    String captchaCode = formDataObj.get("captchaCode").getAsString(); 
    
    // validate captcha 
    SimpleCaptcha captcha = SimpleCaptcha.load(request); 
    boolean isHuman = captcha.validate(captchaCode, captchaId); 
    
    if (isHuman) { 
      // Captcha validation passed 
      // TODO: do whatever you want here 
    } 
    
    // the object that stores validation result 
    ExampleValidationResult validationResult = new ExampleValidationResult(); 
    validationResult.setSuccess(isHuman); 
    
    try { 
      // write the validation result as json string for sending it back to client 
      out.write(gson.toJson(validationResult)); 
    } catch(Exception ex) { 
      out.write(ex.getMessage()); 
    } finally { 
      out.close(); 
    } 
  } 
} 
  • Server-side Captcha validation in a Spring MVC Controller is performed in the following way:
... 
import com.captcha.botdetect.web.servlet.SimpleCaptcha; 

@Controller 
public class ExampleController { 

  @RequestMapping(value = "basic-captcha", method = RequestMethod.POST, produces = "application/json; charset=utf-8") 
  @ResponseBody 
  public String exampleCaptcha(HttpServletRequest request) { 
    JsonParser parser = new JsonParser(); 
    JsonObject formDataObj = null; 
    boolean result = false; 

    try { 
      formDataObj = (JsonObject) parser.parse(request.getReader()); 
    } catch (IOException ex) { } 

    if (formDataObj != null) { 
      String captchaId = formDataObj.get("captchaId").getAsString(); 
      String captchaCode = formDataObj.get("captchaCode").getAsString(); 

      // validate captcha 
      SimpleCaptcha captcha = SimpleCaptcha.load(request); 
      boolean isHuman = captcha.validate(captchaCode, captchaId); 
      
      result = isHuman; 
    } 

    return "{\"success\":" + result.toString() + "}"; 
  } 
} 
  • Server-side Captcha validation in a Struts Action is performed in the following way:
... 
import com.captcha.botdetect.web.servlet.SimpleCaptcha; 

public class ExampleAction { 

  private boolean success = false; 

  public boolean isSuccess() { 
    return success; 
  } 

  public String execute() { 
    HttpServletRequest request = ServletActionContext.getRequest(); 
    
    if (!request.getMethod().equalsIgnoreCase("post")) { 
      return Action.ERROR; 
    } 

    Map<String, String> mapParams = request.getParameterMap(); 
    Set<String> setKeys = mapParams.keySet(); 
    Iterator<String> temp = setKeys.iterator(); 
    String data = temp.next(); 

    JsonParser parser = new JsonParser(); 
    JsonObject formDataObj = (JsonObject) parser.parse(data); 

    if (formDataObj != null) { 
      String captchaId = formDataObj.get("captchaId").getAsString(); 
      String captchaCode = formDataObj.get("captchaCode").getAsString(); 

      // validate captcha 
      SimpleCaptcha captcha = SimpleCaptcha.load(request); 
      boolean isHuman = captcha.validate(captchaCode, captchaId); 
      
      this.success = isHuman; 
    } 

    return Action.SUCCESS; 
  } 
} 

Display Captcha error message in your HTML template

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) { 
  if (!isCorrect) { 
    $('#message').text('Incorrect captcha code') 
  } 
}); 

To display captcha error message, simply listen the custom validatecaptcha event, which will be fired on captcha code input element's blur event and check the second argument (i.e isCorrect in the code above) of the callback function. If it returns false, this means that UI captcha validation failed.

Java server-side Configuration

Install BotDetect Java Captcha library on Server-side

Before integrating BotDetect Captcha in your jQuery application, you need to ensure you have installed BotDetect Java Captcha library on your server where your jQuery application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?xml version="1.0" encoding="UTF-8"?> 
<botdetect xmlns="https://captcha.com/schema/java" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="https://captcha.com/schema/java  
      https://captcha.com/schema/java/botdetect-4.0.beta3.5.xsd"> 

  <captchaStyles> 
    
    <captchaStyle> 
      <name>exampleCaptcha</name> 
      <userInputID>captchaCode</userInputID> 
      <codeLength>6</codeLength> 
    </captchaStyle> 

    <captchaStyle> 
      <name>loginCaptcha</name> 
      <userInputID>captchaCode</userInputID> 
      <codeLength>4-6</codeLength> 
      <codeStyle>ALPHANUMERIC</codeStyle> 
    </captchaStyle> 

  </captchaStyles> 

</botdetect> 

To configure captcha options, you need to create botdetect.xml configuration file (with xml content like the one above this) in WEB-INF/ folder. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

..............................................................

jQuery application with PHP backend

  1. Install BotDetect CAPTCHA jQuery Plugin
  2. Display BotDetect CAPTCHA in HTML template
  3. Captcha Validation
  4. PHP server-side Configuration

Install BotDetect CAPTCHA jQuery Plugin

Step 1: Install BotDetect Captcha jQuery Plugin

Step 2: Include BotDetect Captcha jQuery Plugin in your web app

<script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 

Step 3: Load BotDetect Captcha jQuery Plugin in your application

The following step ensures that BotDetect CAPTCHA library works properly in your jQuery application. Please follow it carefully.

$(document).ready(function() { 
    // DOM ready 

    var captcha = $('#botdetect-captcha').captcha({ 
      captchaEndpoint: 'captcha-endpoint/simple-botdetect.php' 
    }); 

}); 

When DOM is loaded, we load jQuery Captcha plugin using the .captcha() method -- passing the captchaEndpoint setting which represents the path where BotDetect PHP Captcha responds. The captcha JavaScript object exposes all Captcha workflow functions and vars that we will use later during the form submission part of the workflow.

Before you set the path to captchaEndpoint setting, we need to clarify what we set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect PHP Captcha library. If you deployed BotDetect PHP Captcha library in the root of your domain, then you don't need to set this path.
  • /simple-botdectect.php is the Handler URL of the PHP script processing Captcha challenge Http requests and this if you use the BotDetect Captcha library in a Plain PHP application. Use /simple-captcha-handler if you use the following:

To ensure that you have set a right path to captchaEndpoint setting, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/simple-botdetect.php (replace the exact path of your domain). If this results with an error message ("unknown command") then you set the right path, since that is the BotDetect Captcha that responded with error (when you fail to set correct path, then your server will respond with 404 instead). Please note, in order to perform this check, BotDetect Captcha Generator needs to be installed & deployed to your server.

Display BotDetect CAPTCHA In Your HTML Template

Displaying the Captcha challenge can be as simple as:

<div id="botdetect-captcha" data-stylename="exampleCaptcha"></div> 

You simply declare a HTML element and assign data-stylename attribute a captcha style name defined in botdetect.xml configuration file.

The captcha html markup will be displayed as soon as you load the jQuery Captcha plugin in your application as described in the Step 3 above.

Captcha Validation

Client-side Captcha validation in your jQuery application

BotDetect Captcha jQuery Plugin provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
// On form submit 
$('#exampleForm').submit(function(event) { 

  captcha.validateUnsafe(function(isCaptchaCodeCorrect) { 

    if (isCaptchaCodeCorrect) { 
      // Captcha code is correct 
    } else { 
      // Captcha code is incorrect 
    } 
    
  }); 

  event.preventDefault(); 
}); 

OR:

  • Using data-correct-captcha directive attribute to validate Captcha code on blur event:

You need to add the data-correct-captcha attribute in the captcha code input element. BotDetect Captcha jQuery will then automatically validate captcha code on blur event.

<input 
  type="text" 
  name="captchaCode" 
  id="captchaCode" 
  data-correct-captcha 
> 

And you can check the captcha validation result by listing the custom validatecaptcha event as the code shown below.

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) { 
  if (isCorrect) { 
    // UI Captcha validation passed 
  } else { 
    // UI Captcha validation failed 
  } 
}) 

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

PHP Server-side Captcha validation

$('#exampleForm').submit(function(event) { 
  
  // captcha id for validating captcha at server-side 
  var captchaId = captcha.getCaptchaId(); 

  // captcha code input value for validating captcha at server-side 
  var captchaCode = $('#captchaCode').val(); 

  var postData = { 
    captchaId: captchaId, 
    captchaCode: captchaCode 
  }; 

  $.ajax({ 
    method: 'POST', 
    url: '/your-server-side-api-url', 
    dataType: 'json', 
    contentType: 'application/json', 
    data: JSON.stringify(postData), 
    success: function(response) { 
      if (response.success) { 
        // captcha validation passed at server-side 
      } else { 
        // captcha validation failed at server-side 
      } 
    }, 
    complete: function() { 
      // we should reload captcha image after server-side validation is completed 
      // in order to update new captcha code for current captcha id 
      captcha.reloadImage(); 
    } 
  }); 
 
}); 

To validate Captcha at server-side, we need to send captchaId property of captcha JavaScript object and captcha code visitor submited to server-side.

Once request finished, we always reload Captcha by calling the reloadImage() function of captcha JavaScript object. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using Validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • Server-side Captcha validation in Plain PHP:
<?php 
require("captcha-endpoint/simple-botdetect.php"); 

// directly accessing this script is an error 
if (!$_SERVER['REQUEST_METHOD'] == "POST") { 
  header("HTTP/1.1 400 Bad Request"); 
  exit; 
} 

$inputJSON = file_get_contents('php://input'); 
$input = json_decode($inputJSON, TRUE); 
$userInput = $input["captchaCode"]; 
$captchaId = $input["captchaId"]; 

// Captcha validation 
$ExampleCaptcha = new SimpleCaptcha(); 
$isHuman = $ExampleCaptcha->Validate($userInput, $captchaId); 

if ($isHuman) { 
  // Captcha validation passed 
  // TODO: do whatever you want here 
} 
$result = array('success' => $isHuman); 
echo json_encode($result, true); 
exit; 
  • Server-side Captcha validation in Symfony:
<?php 

namespace AppBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class ExampleController extends Controller 
{ 
  /** 
   * @Route("/api/example", methods={"POST"}) 
   */ 
  public function postExampleAction(Request $request) 
  { 
    $postData = json_decode($request->getContent()); 
     
    $captchaCode = $postData->captchaCode; 
    $captchaId = $postData->captchaId; 

    // validate captcha 
    $captcha = $this->container->get('simple_captcha')->getInstance(); 
    $isHuman = $captcha->Validate($captchaCode, $captchaId); 
    
    if ($isHuman) { 
      // Captcha validation passed 
      // TODO: do whatever you want here 
    } 

    // write the validation result as json string for sending it back to client 
    $response = array('success' => $isHuman); 
    return $this->json($response); 
  } 
} 
  • Server-side Captcha validation in Laravel:
<?php namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

class ExampleController extends Controller 
{ 
  public function postAction(Request $request) 
  { 
    $captchaCode = $request->input('captchaCode'); 
    $captchaId = $request->input('captchaId'); 
    
    // validate captcha 
    $isHuman = simple_captcha_validate($captchaCode, $captchaId); 

    if ($isHuman) { 
      // Captcha validation passed 
      // TODO: do whatever you want here 
    } 
   
    // write the validation result as json string for sending it back to client 
    $response = array('success' => $isHuman); 
    return response()->json($response); 
  } 
} 
  • Server-side Captcha validation in CakePHP:
<?php 

namespace App\Controller; 

use Cake\Controller\Controller; 

class ExampleController extends Controller 
{ 
  public function initialize() 
  { 
    parent::initialize(); 

    // load the Simple Captcha component 
    $this->loadComponent('CakeCaptcha.SimpleCaptcha'); 
  } 

  public function postExampleAction() 
  { 
    $this->autoRender = false; 
    
    if ($this->request->is('post')) { 
      $captchaCode = $this->request->data['captchaCode']; 
      $captchaId = $this->request->data['captchaId']; 
      
      // validate captcha 
      $isHuman = simple_captcha_validate($captchaCode, $captchaId); 

      if ($isHuman) { 
        // Captcha validation passed 
        // TODO: do whatever you want here 
      } 

      // write the validation result as json string for sending it back to client 
      $result = array('success' => $isHuman); 
      return $this->response->withType('application/json') 
              ->withStringBody(json_encode($result)); 
    } 
  } 
} 
  • Server-side Captcha validation in CodeIgniter:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Example extends CI_Controller { 

  public function postExampleAction() 
  { 
    // load the BotDetect Captcha library 
    $this->load->library('botdetect/BotDetectSimpleCaptcha'); 

    $captchaCode = $this->input->post('captchaCode'); 
    $captchaId = $this->input->post('captchaId'); 

    // validate captcha 
    $isHuman = $this->botdetectsimplecaptcha->Validate($captchaCode, $captchaId); 

    if ($isHuman) { 
      // Captcha validation passed 
      // TODO: do whatever you want here 
    } 

    // write the validation result as json string for sending it back to client 
    $result = array('success' => $isHuman); 

    return $this->output 
      ->set_content_type('application/json') 
      ->set_output(json_encode($result)); 
  } 
} 

Display Captcha error message in your HTML template

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) { 
  if (!isCorrect) { 
    $('#message').text('Incorrect captcha code') 
  } 
}); 

To display captcha error message, simply listen the custom validatecaptcha event, which will be fired on captcha code input element's blur event and check the second argument (i.e isCorrect in the code above) of the callback function. If it returns false, this means that UI captcha validation failed.

PHP server-side Configuration

Install BotDetect PHP Captcha library on Server-side

Before integrating BotDetect Captcha in your jQuery application, you need to ensure you have installed BotDetect PHP Captcha library on your server where your jQuery application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?xml version="1.0" encoding="UTF-8"?> 
<botdetect xmlns="https://captcha.com/schema/php" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
           xsi:schemaLocation="https://captcha.com/schema/php 
            https://captcha.com/schema/php/botdetect-4.2.3.xsd"> 

  <captchaStyles> 
    <captchaStyle> 
      <name>exampleCaptcha</name> 
      <userInputID>captchaCode</userInputID> 
      <codeLength>3-5</codeLength> 
      <helpLinkMode>Image</helpLinkMode> 
    </captchaStyle> 

    <captchaStyle> 
      <name>jqueryFormCaptcha</name> 
      <userInputID>captchaCode</userInputID> 
      <codeLength>4-6</codeLength> 
      <helpLinkMode>Image</helpLinkMode> 
    </captchaStyle> 
  </captchaStyles> 

</botdetect> 

All BotDetect captcha options will be configured in config/botdetect.xml configuration file. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Please Note

jQuery Captcha Plugin requires the new experimental Simple API that is currently available in BotDetect Java v4.0.Beta3+, BotDetect PHP v4.2.0+, as well as in BotDetect ASP.NET v4.4.0 build for legacy .NET.
The Simple API for ASP.NET Core will be available in the BotDetect ASP.NET v4.4.1 that will be released in few weeks time.