jQuery Captcha Plugin: The Simple API Usage Example

Click on the link below that matches your BotDetect CAPTCHA jQuery Plugin usage scenario:

First Time Here?

The jQuery CAPTCHA Integration Guide is the best place to start!

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

jQuery-based Frontend and the web API with ASP.NET Core MVC (MVC6) on Backend

This is a partial walk-through of the example source code. It is not meant to replace a proper step-by-step guide. If you are new to BotDetect, skip it for now; and do start your first jQuery captcha integration by following our step-by-step jQuery CAPTCHA Integration Guide.

Introduction

This basic jQuery captcha example shows the minimal code required to display and validate captchas in an application with a jQuery frontend and a web API with ASP.NET Core MVC (MVC6) backend.

Download the BotDetect ASP.NET CAPTCHA Component and run this example

Within this page, the folder where you installed BotDetect will be referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/aspnetcore+netcore/Examples/SimpleAPI/
jQueryWebAPIwithMVC6CaptchaExample/
folder; and contains the following files:

Frontend: basic.html

The wwwroot/basic.html source file does the following:

  • Loads the BotDetect CAPTCHA jQuery Plugin into the page
  • Displays the captcha and user-input markups on the page
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <title>BotDetect jQuery CAPTCHA Examples</title> 
  <link href="styles/styles.css" type="text/css" rel="stylesheet"> 
</head> 
<body> 
    <header> 
        <div class="header-content"><h1>BotDetect jQuery CAPTCHA Examples</h1></div> 
    </header> 

    <nav> 
      <ul class="nav"> 
        <li><a href="basic.html" class="active">Basic Example</a></li> 
        <li><a href="contact.html">Contact Example</a></li> 
      </ul> 
    </nav> 

    <section id="main-content"> 
        <form id="basicForm" method="POST"> 
            <div id="form-messages"></div> 

            <!-- captcha challenge: placeholder --> 
            <div id="botdetect-captcha" data-captchastylename="jqueryBasicCaptcha"></div> 

            <label> 
                <span>Retype the characters from the picture:</span> 
                <!-- captcha code: user-input textbox --> 
                <input 
                    type="text" 
                    id="userCaptchaInput" 
                > 
            </label> 

            <button type="submit" id="submitButton">Validate</button> 
        </form> 
    </section> 
    
    <script src="node_modules/jquery/jquery.min.js"></script> 
    <script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 
    <script src="js/basic.js"></script> 
</body> 
</html> 

Frontend: basic.js

The wwwroot/js/basic.js source file does the following:

  • Sets the captchaEndpoint property to point to the captcha endpoint path on backend
  • Loads the captcha challenges from backend
  • Sends the post request with the captcha id and the user entered captcha code to backend
  • Processes the captcha validation results:
    • when the captcha validation fails -- it reloads captcha and displays an error message
    • when the captcha validation succeeds -- it executes by the captcha protected action
$(function () { 

    // create the frontend captcha instance in the DOM.ready event-handler; 
    // and set the captchaEndpoint property to point to  
    // the captcha endpoint path on your app's backend 
    var captcha = $('#botdetect-captcha').captcha({ 
        captchaEndpoint: 'simple-captcha-endpoint.ashx' 
    }); 

    // process the form on submit event 
    $('#basicForm').submit(function (event) { 

        // get the user-entered captcha code value to be validated at the backend side 
        var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); 

        // get the id of a captcha instance that the user tried to solve 
        var captchaId = captcha.getCaptchaId(); 

        var postData = { 
            // add the user-entered captcha code value to the post data 
            userEnteredCaptchaCode: userEnteredCaptchaCode, 
            // add the id of a captcha instance to the post data 
            captchaId: captchaId 
        }; 

        // post the captcha data to the backend 
        $.ajax({ 
            method: 'POST', 
            url: 'api/basic-captcha', 
            data: JSON.stringify(postData), 
            contentType: "application/json", 
            success: function (response) { 
                if (response.success == false) { 
                    // captcha validation failed; show the error message 
                    $('#form-messages') 
                        .removeClass() 
                        .addClass('alert alert-error') 
                        .text('CAPTCHA validation falied.'); 
                    // call the captcha.reloadImage() 
                    // in order to generate a new captcha challenge 
                    captcha.reloadImage(); 
                } else { 
                    // captcha validation succeeded; proceed with the workflow 
                    window.location.replace('notify_page/basic_success_notify.html'); 
                } 
            }, 
            error: function (error) { 
                throw new Error(error); 
            } 
        }); 

        event.preventDefault(); 
    }); 
}); 

Backend: appsettings.json

The appsettings.json source file contains the following:

  • BotDetect configuration section that defines the CaptchaEndpointPath path
{ 
  "Logging": { 
    "IncludeScopes": false, 
    "LogLevel": { 
      "Default": "Warning" 
    } 
  }, 
  "BotDetect": { 
    "CaptchaEndpointPath": "simple-captcha-endpoint.ashx" 
  } 
} 

Backend: Startup.cs

The Startup.cs source file does the following:

  • Configures the application pipeline to use SimpleCaptcha middleware
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Http; 
using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Logging; 

using BotDetect.Web; 
using BotDetect.Web.Http; 

namespace jQueryWebAPIwithMVC6CaptchaExample 
{ 
    public class Startup 
    { 
        public Startup(IHostingEnvironment env) 
        { 
            var builder = new ConfigurationBuilder() 
                .SetBasePath(env.ContentRootPath) 
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
                .AddEnvironmentVariables(); 
            Configuration = builder.Build(); 
        } 

        public IConfigurationRoot Configuration { get; } 

        // This method gets called by the runtime. Use this method to add services to the container. 
        public void ConfigureServices(IServiceCollection services) 
        { 
            // You can omit the next line on .NET Core 2.0 or higher 
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

            services.AddMemoryCache(); // Adds a default in-memory  
                                       // implementation of  
                                       // IDistributedCache 

            // Add framework services. 
            services.AddMvc(); 
        } 

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
        { 
            loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
            loggerFactory.AddDebug(); 

            if (env.IsDevelopment()) 
            { 
                app.UseDeveloperExceptionPage(); 
            } 

            // Serve my app-specific default file, if present. 
            DefaultFilesOptions options = new DefaultFilesOptions(); 
            options.DefaultFileNames.Clear(); 
            options.DefaultFileNames.Add("basic.html"); 
            app.UseDefaultFiles(options); 
            app.UseStaticFiles(); 

            // Configure the application pipeline to use SimpleCaptcha middleware 
            app.UseSimpleCaptcha(Configuration.GetSection("BotDetect")); 

            app.UseMvc(); 
        } 
    } 
} 

Backend: botdetect.xml

The botdetect.xml source file contains the following:

  • Captcha style definitions consisting of:
    • The name of a captcha style
    • The ID of an <input> element in which user enters captcha codes
    • Other option settings -- the captcha code length in this particular case
<?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.1.xsd"> 

  <captchaStyles> 
    <captchaStyle> 
      <name>jqueryBasicCaptcha</name> 
      <userInputID>userCaptchaInput</userInputID> 
      <codeLength>3-5</codeLength> 
    </captchaStyle> 
  </captchaStyles> 
</botdetect> 

Backend: BasicApiController.cs

The Controllers/BasicApiController.cs source file does the following:

  • Extracts the userEnteredCaptchaCode and captchaId values posted from the frontend
  • Validates captchas by calling the Validate(userEnteredCaptchaCode, captchaId) method
  • Returns the json-formatted captcha validation results to frontend
using Microsoft.AspNetCore.Mvc; 
using System.Collections.Generic; 

using BotDetect.Web; 

namespace jQueryWebAPIwithMVC6CaptchaExample.Controllers 
{ 
    [Produces("application/json")] 
    [Route("api/basic-captcha")] 
    public class BasicApiController : Controller 
    { 
        [HttpPost] 
        public IActionResult Post([FromBody] Models.BasicFormModel data) 
        { 
            // create a captcha instance to be used for the captcha validation 
            SimpleCaptcha captcha = new SimpleCaptcha(); 
            // execute the captcha validation 
            bool isHuman = captcha.Validate(data.UserEnteredCaptchaCode, data.CaptchaId); 

            // create an object that stores the validation result 
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>(); 

            if (isHuman == false) 
            { 
                // captcha validation failed 
                validationResult.Add("success", false); 
                // TODO: consider logging the attempt 
            } 
            else 
            { 
                // captcha validation succeeded 
                validationResult.Add("success", true); 
            } 

            // return the json string with the validation result to the frontend 
            return Json(validationResult); 
        } 
    } 
} 

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

jQuery-based Frontend and the Legacy ASP.NET Web-API 2 on Backend

This is a partial walk-through of the example source code. It is not meant to replace a proper step-by-step guide. If you are new to BotDetect, skip it for now; and do start your first jQuery captcha integration by following our step-by-step jQuery CAPTCHA Integration Guide.

Introduction

This basic jQuery captcha example shows the minimal code required to display and validate captchas in an application with a jQuery frontend and a legacy ASP.NET Web-API 2 backend.

Download the BotDetect ASP.NET CAPTCHA Component and run this example

Within this page, the folder where you installed BotDetect will be referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/aspnetlegacy+netlegacy/Examples/SimpleAPI/
jQueryWebAPICaptchaExample/CSharp/
folder; and contains the following files:

Frontend: basic.html

The basic.html source file does the following:

  • Loads the BotDetect CAPTCHA jQuery Plugin into the page
  • Displays the captcha and user-input markups on the page
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <title>BotDetect jQuery CAPTCHA Examples</title> 
  <link href="styles/styles.css" type="text/css" rel="stylesheet"> 
</head> 
<body> 
    <header> 
        <div class="header-content"><h1>BotDetect jQuery CAPTCHA Examples</h1></div> 
    </header> 

    <nav> 
      <ul class="nav"> 
        <li><a href="basic.html" class="active">Basic Example</a></li> 
        <li><a href="contact.html">Contact Example</a></li> 
      </ul> 
    </nav> 

    <section id="main-content"> 
        <form id="basicForm" method="POST"> 
            <div id="form-messages"></div> 

            <!-- captcha challenge: placeholder --> 
            <div id="botdetect-captcha" data-captchastylename="jqueryBasicCaptcha"></div> 

            <label> 
                <span>Retype the characters from the picture:</span> 
                <!-- captcha code: user-input textbox --> 
                <input 
                    type="text" 
                    id="userCaptchaInput" 
                > 
            </label> 

            <button type="submit" id="submitButton">Validate</button> 
        </form> 
    </section> 
    
    <script src="node_modules/jquery/jquery.min.js"></script> 
    <script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 
    <script src="js/basic.js"></script> 
</body> 
</html> 

Frontend: basic.js

The js/basic.js source file does the following:

  • Sets the captchaEndpoint property to point to the captcha endpoint path on backend
  • Loads the captcha challenges from backend
  • Sends the post request with the captcha id and the user entered captcha code to backend
  • Processes the captcha validation results:
    • when the captcha validation fails -- it reloads captcha and displays an error message
    • when the captcha validation succeeds -- it executes by the captcha protected action
$(function () { 

    // create the frontend captcha instance in the DOM.ready event-handler; 
    // and set the captchaEndpoint property to point to  
    // the captcha endpoint path on your app's backend 
    var captcha = $('#botdetect-captcha').captcha({ 
        captchaEndpoint: 'simple-captcha-endpoint.ashx' 
    }); 

    // process the form on submit event 
    $('#basicForm').submit(function (event) { 

        // get the user-entered captcha code value to be validated at the backend side         
        var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); 

        // get the id of a captcha instance that the user tried to solve 
        var captchaId = captcha.getCaptchaId(); 

        var postData = { 
            // add the user-entered captcha code value to the post data 
            userEnteredCaptchaCode: userEnteredCaptchaCode, 
            // add the id of a captcha instance to the post data 
            captchaId: captchaId 
        }; 

        // post the captcha data to the backend 
        $.ajax({ 
            method: 'POST', 
            url: 'api/webapi/basic', 
            data: JSON.stringify(postData), 
            contentType: "application/json", 
            success: function (response) { 
                if (response.success == false) { 
                    // captcha validation failed; show the error message 
                    $('#form-messages') 
                        .removeClass() 
                        .addClass('alert alert-error') 
                        .text('CAPTCHA validation falied.'); 
                    // call the captcha.reloadImage() 
                    // in order to generate a new captcha challenge 
                    captcha.reloadImage(); 
                } else { 
                    // captcha validation succeeded; proceed with the workflow 
                    window.location.replace('notify_page/basic_success_notify.html'); 
                } 
            }, 
            error: function (error) { 
                throw new Error(error); 
            } 
        }); 

        event.preventDefault(); 
    }); 
}); 

Backend: web.config

The web.config source file does the following:

  • Registers the simple-captcha-endpoint.ashx path
  • Maps it to the BotDetect.Web.SimpleCaptchaHandler
<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
  <appSettings></appSettings> 
  <system.web> 
    <compilation debug="false" targetFramework="4.5"/> 
    <httpRuntime targetFramework="4.5"/> 
    <httpHandlers> 
      <!-- Register the HttpHandler used for BotDetect Captcha requests --> 
      <add verb="GET" path="simple-captcha-endpoint.ashx" 
	   type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> 
    </httpHandlers> 
  </system.web> 
  <system.webServer> 
    <validation validateIntegratedModeConfiguration="false"/> 
    <handlers> 
      <!-- Register the HttpHandler used for BotDetect Captcha requests (IIS 7.0+) --> 
      <remove name="BotDetectCaptchaHandler"/> 
      <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
	   verb="GET" path="simple-captcha-endpoint.ashx" 
	   type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> 
    </handlers> 
    <defaultDocument> 
      <files> 
        <clear /> 
        <add value="basic.html"/> 
      </files> 
    </defaultDocument> 
  </system.webServer> 
</configuration> 

Backend: botdetect.xml

The botdetect.xml source file contains the following:

  • Captcha style definitions consisting of:
    • The name of a captcha style
    • The ID of an <input> element in which user enters captcha codes
    • Other option settings -- the captcha code length in this particular case
<?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.1.xsd"> 

    <captchaStyles> 
        <captchaStyle> 
            <name>jqueryBasicCaptcha</name> 
            <userInputID>userCaptchaInput</userInputID> 
            <codeLength>3-5</codeLength> 
        </captchaStyle> 
    </captchaStyles> 
</botdetect> 

Backend: WebApiController.cs

The Backend/Controllers/WebApiController.cs source file does the following:

  • Extracts the userEnteredCaptchaCode and captchaId values posted from the frontend
  • Validates captchas by calling the Validate(userEnteredCaptchaCode, captchaId) method
  • Returns the json-formatted captcha validation results to frontend
using System.Collections.Generic; 
using System.Text.RegularExpressions; 
using System.Web.Http; 
using jQueryWebAPICaptchaExampleCSharp.Backend.Models; 

using BotDetect.Web; 

namespace jQueryWebAPICaptchaExampleCSharp.Backend.Controllers 
{ 
    public class WebApiController : ApiController 
    { 
        // POST api/webapi/basic 
        public IHttpActionResult Basic([FromBody]CaptchaBasicModel data) 
        { 
            // create a captcha instance to be used for the captcha validation 
            SimpleCaptcha captcha = new SimpleCaptcha(); 
            // execute the captcha validation 
            bool isHuman = captcha.Validate(data.UserEnteredCaptchaCode, data.CaptchaId); 

            // create an object that stores the validation result 
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>(); 

            if (isHuman == false) 
            { 
                // captcha validation failed 
                validationResult.Add("success", false); 
                // TODO: consider logging the attempt 
            } 
            else 
            { 
                // captcha validation succeeded 
                validationResult.Add("success", true); 
            } 

            // return the json string with the validation result to the frontend 
            return Ok(validationResult); 
        } 
    } 
	
    public class CaptchaBasicModel 
    { 
        [JsonProperty("captchaId")] 
        public string CaptchaId { get; set; } 

        [JsonProperty("userEnteredCaptchaCode")] 
        public string UserEnteredCaptchaCode { get; set; } 
    } 
} 

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

jQuery-based Frontend and the Legacy ASP.NET Generic Handler on Backend

This is a partial walk-through of the example source code. It is not meant to replace a proper step-by-step guide. If you are new to BotDetect, skip it for now; and do start your first jQuery captcha integration by following our step-by-step jQuery CAPTCHA Integration Guide.

Introduction

This basic jQuery captcha example shows the minimal code required to display and validate captchas in an application with a jQuery frontend and a legacy ASP.NET Generic Handler backend.

Download the BotDetect ASP.NET CAPTCHA Component and run this example

Within this page, the folder where you installed BotDetect will be referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/aspnetlegacy+netlegacy/Examples/SimpleAPI/
jQueryCaptchaExample/CSharp/
folder; and contains the following files:

Frontend: basic.html

The basic.html source file does the following:

  • Loads the BotDetect CAPTCHA jQuery Plugin into the page
  • Displays the captcha and user-input markups on the page
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <title>BotDetect jQuery CAPTCHA Examples</title> 
  <link href="styles/styles.css" type="text/css" rel="stylesheet"> 
</head> 
<body> 
    <header> 
        <div class="header-content"><h1>BotDetect jQuery CAPTCHA Examples</h1></div> 
    </header> 

    <nav> 
      <ul class="nav"> 
        <li><a href="basic.html" class="active">Basic Example</a></li> 
        <li><a href="contact.html">Contact Example</a></li> 
      </ul> 
    </nav> 

    <section id="main-content"> 
        <form id="basicForm" method="POST"> 
            <div id="form-messages"></div> 

            <!-- captcha challenge: placeholder --> 
            <div id="botdetect-captcha" data-captchastylename="jqueryBasicCaptcha"></div> 

            <label> 
                <span>Retype the characters from the picture:</span> 
                <!-- captcha code: user-input textbox --> 
                <input 
                    type="text" 
                    id="userCaptchaInput" 
                > 
            </label> 

            <button type="submit" id="submitButton">Validate</button> 
        </form> 
    </section> 
    
    <script src="node_modules/jquery/jquery.min.js"></script> 
    <script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 
    <script src="js/basic.js"></script> 
</body> 
</html> 

Frontend: basic.js

The js/basic.js source file does the following:

  • Sets the captchaEndpoint property to point to the captcha endpoint path on backend
  • Loads the captcha challenges from backend
  • Sends the post request with the captcha id and the user entered captcha code to backend
  • Processes the captcha validation results:
    • when the captcha validation fails -- it reloads captcha and displays an error message
    • when the captcha validation succeeds -- it executes by the captcha protected action
$(function () { 

    // create the frontend captcha instance in the DOM.ready event-handler; 
    // and set the captchaEndpoint property to point to  
    // the captcha endpoint path on your app's backend 
    var captcha = $('#botdetect-captcha').captcha({ 
        captchaEndpoint: 'simple-captcha-endpoint.ashx' 
    }); 

    // process the form on submit event 
    $('#basicForm').submit(function (event) { 

        // get the user-entered captcha code value to be validated at the backend side         
        var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); 

        // get the id of a captcha instance that the user tried to solve 
        var captchaId = captcha.getCaptchaId(); 

        var postData = { 
            // add the user-entered captcha code value to the post data 
            userEnteredCaptchaCode: userEnteredCaptchaCode, 
            // add the id of a captcha instance to the post data 
            captchaId: captchaId 
        }; 

        // post the captcha data to the backend 
        $.ajax({ 
            method: 'POST', 
            url: 'form/BasicHandler.ashx', 
            dataType: 'json', 
            contentType: 'application/json', 
            data: JSON.stringify(postData), 
            success: function (response) { 
                if (response.success == false) { 
                    // captcha validation failed; show the error message 
                    $('#form-messages') 
                        .removeClass() 
                        .addClass('alert alert-error') 
                        .text('CAPTCHA validation falied.'); 
                    // call the captcha.reloadImage() 
                    // in order to generate a new captcha challenge 
                    captcha.reloadImage(); 
                } else { 
                    // captcha validation succeeded; proceed with the workflow 
                    window.location.replace('notify_page/basic_success_notify.html'); 
                } 
            }, 
            error: function (error) { 
                throw new Error(error); 
            } 
        }); 

        event.preventDefault(); 
    }); 
}); 

Backend: web.config

The web.config source file does the following:

  • Registers the simple-captcha-endpoint.ashx path
  • Maps it to the BotDetect.Web.SimpleCaptchaHandler
<?xml version="1.0" encoding="UTF-8"?> 
<configuration> 
  <system.web> 
    <compilation debug="true" targetFramework="4.5"/> 
    <httpRuntime targetFramework="4.5"/> 
    <httpHandlers> 
      <!-- Register the HttpHandler used for BotDetect Captcha requests --> 
      <add verb="GET" path="simple-captcha-endpoint.ashx" 
           type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> 
    </httpHandlers> 
  </system.web> 
  <system.webServer> 
    <validation validateIntegratedModeConfiguration="false" /> 
    <handlers> 
      <!-- Register the HttpHandler used for BotDetect Captcha requests (IIS 7.0+) --> 
      <remove name="BotDetectCaptchaHandler"/> 
      <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
           verb="GET" path="simple-captcha-endpoint.ashx" 
           type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> 
    </handlers> 
    <defaultDocument> 
      <files> 
        <clear /> 
        <add value="basic.html"/> 
      </files> 
    </defaultDocument> 
  </system.webServer> 
</configuration> 

Backend: botdetect.xml

The botdetect.xml source file contains the following:

  • Captcha style definitions consisting of:
    • The name of a captcha style
    • The ID of an <input> element in which user enters captcha codes
    • Other option settings -- the captcha code length in this particular case
<?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.1.xsd"> 

    <captchaStyles> 
        <captchaStyle> 
            <name>jqueryBasicCaptcha</name> 
            <userInputID>userCaptchaInput</userInputID> 
            <codeLength>3-5</codeLength> 
        </captchaStyle> 
    </captchaStyles> 
</botdetect> 

Backend: BasicHandler.ashx

The form/BasicHandler.ashx source file does the following:

  • Extracts the userEnteredCaptchaCode and captchaId values posted from the frontend
  • Validates captchas by calling the Validate(userEnteredCaptchaCode, captchaId) method
  • Returns the json-formatted captcha validation results to frontend
<%@ 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 userEnteredCaptchaCode = formDataObj["userEnteredCaptchaCode"]; 
            string captchaId = formDataObj["captchaId"]; 

            // create a captcha instance to be used for the captcha validation 
            SimpleCaptcha captcha = new SimpleCaptcha(); 
            // execute the captcha validation 
            bool isHuman = captcha.Validate(userEnteredCaptchaCode, captchaId); 
           
            // create an object that stores the validation result 
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>(); 

            if (isHuman == false) 
            { 
                // captcha validation failed 
                validationResult.Add("success", false); 
            } 
            else 
            { 
                // captcha validation succeeded 
                validationResult.Add("success", true); 
            } 

            // return the json string with the validation result to the frontend 
            context.Response.ContentType = "application/json; charset=utf-8"; 
            context.Response.Write(JsonConvert.SerializeObject(validationResult)); 
        } 
        else 
        { 
            context.Response.ContentType = "text/plain"; 
            context.Response.Write("Only HTTP POST requests are allowed."); 
        } 
    } 

    public bool IsReusable 
    { 
        get 
        { 
            return false; 
        } 
    } 
} 

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

jQuery-based Frontend and Java Servlet on Backend

This is a partial walk-through of the example source code. It is not meant to replace a proper step-by-step guide. If you are new to BotDetect, skip it for now; and do start your first jQuery captcha integration by following our step-by-step jQuery CAPTCHA Integration Guide.

Introduction

This basic jQuery captcha example shows the minimal code required to display and validate captchas in an application with a jQuery frontend and a Java Servlet backend.

Download the BotDetect Java CAPTCHA Library archive and run this example

Within this page, the root folder of the extracted archive is referred as the <BDC-DIR>

This example is in the <BDC-DIR>/examples/simple-api-jquery-captcha-example/ folder; and contains the following files:

Frontend: basic.html

The src/main/webapp/basic.html source file does the following:

  • Loads the BotDetect CAPTCHA jQuery Plugin into the page
  • Displays the captcha and user-input markups on the page
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <title>BotDetect jQuery CAPTCHA Examples</title> 
  <link href="styles/styles.css" type="text/css" rel="stylesheet"> 
</head> 
<body> 
    <header> 
        <div class="header-content"><h1>BotDetect jQuery CAPTCHA Examples</h1></div> 
    </header> 

    <nav> 
      <ul class="nav"> 
        <li><a href="basic.html" class="active">Basic Example</a></li> 
        <li><a href="contact.html">Contact Example</a></li> 
      </ul> 
    </nav> 

    <section id="main-content"> 
        <form id="basicForm" method="POST"> 
            <div id="form-messages"></div> 

            <!-- captcha challenge: placeholder --> 
            <div id="botdetect-captcha" data-captchastylename="jqueryBasicCaptcha"></div> 

            <label> 
                <span>Retype the characters from the picture:</span> 
                <!-- captcha code: user-input textbox --> 
                <input 
                    type="text" 
                    id="userCaptchaInput" 
                > 
            </label> 

            <button type="submit" id="submitButton">Validate</button> 
        </form> 
    </section> 
    
    <script src="node_modules/jquery/jquery.min.js"></script> 
    <script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 
    <script src="js/basic.js"></script> 
</body> 
</html> 

Frontend: jbasic.js

The src/main/webapp/js/basic.js source file does the following:

  • Sets the captchaEndpoint property to point to the captcha endpoint path on backend
  • Loads the captcha challenges from backend
  • Sends the post request with the captcha id and the user entered captcha code to backend
  • Processes the captcha validation results:
    • when the captcha validation fails -- it reloads captcha and displays an error message
    • when the captcha validation succeeds -- it executes by the captcha protected action
$(function () { 

    // create the frontend captcha instance in the DOM.ready event-handler; 
    // and set the captchaEndpoint property to point to  
    // the captcha endpoint path on your app's backend 
    var captcha = $('#botdetect-captcha').captcha({ 
        captchaEndpoint: 'simple-captcha-endpoint' 
    }); 


    // process the form on submit event 
    $('#basicForm').submit(function (event) { 

        // get the user-entered captcha code value to be validated at the backend side         
        var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); 

        // get the id of a captcha instance that the user tried to solve 
        var captchaId = captcha.getCaptchaId(); 

        var postData = { 
            // add the user-entered captcha code value to the post data 
            userEnteredCaptchaCode: userEnteredCaptchaCode, 
            // add the id of a captcha instance to the post data 
            captchaId: captchaId 
        }; 

        // post the captcha data to the backend 
        $.ajax({ 
            method: 'POST', 
            url: 'basic-captcha', 
            dataType: 'json', 
            contentType: 'application/json', 
            data: JSON.stringify(postData), 
            success: function (response) { 
                if (response.success == false) { 
                    // captcha validation failed; show the error message 
                    $('#form-messages') 
                        .removeClass() 
                        .addClass('alert alert-error') 
                        .text('CAPTCHA validation falied.'); 
                    // call the captcha.reloadImage() 
                    // in order to generate a new captcha challenge 
                    captcha.reloadImage(); 
                } else { 
                    // captcha validation succeeded; proceed with the workflow 
                    window.location.replace('notify_page/basic_success_notify.html'); 
                } 
            }, 
            error: function (error) { 
                throw new Error(error); 
            } 
        }); 

        event.preventDefault(); 
    }); 
}); 

Backend: web.xml

The src/main/webapp/WEB-INF/web.xml source file does the following:

  • Registers the simple-captcha-endpoint path
  • Maps it to the com.captcha.botdetect.web.servlet.SimpleCaptchaServlet
<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
    <session-config> 
        <session-timeout> 
            30 
        </session-timeout> 
    </session-config> 
    <servlet> 
        <servlet-name>BotDetect Captcha</servlet-name> 
        <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>BotDetect Captcha</servlet-name> 
        <url-pattern>/simple-captcha-endpoint</url-pattern> 
    </servlet-mapping> 
    <servlet> 
        <servlet-name>Basic Captcha</servlet-name> 
        <servlet-class>com.captcha.botdetect.examples.jquery.basic_form.BasicServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>Basic Captcha</servlet-name> 
        <url-pattern>/basic-captcha</url-pattern> 
    </servlet-mapping> 
    <welcome-file-list> 
        <welcome-file>basic.html</welcome-file> 
    </welcome-file-list> 
</web-app> 

Backend: botdetect.xml

The src/main/webapp/WEB-INF/botdetect.xml source file contains the following:

  • Captcha style definitions consisting of:
    • The name of a captcha style
    • The ID of an <input> element in which user enters captcha codes
    • Other option settings -- the captcha code length in this particular case
<?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.6.xsd"> 

    <captchaStyles> 
        <captchaStyle> 
            <name>jqueryBasicCaptcha</name> 
            <userInputID>userCaptchaInput</userInputID> 
            <codeLength>3-5</codeLength> 
        </captchaStyle> 
    </captchaStyles> 
</botdetect> 

Backend: BasicServlet.java

The src/main/java/com/captcha/botdetect/examples/jquery/basic_form/
BasicServlet.java
source file does the following:

  • Extracts the userEnteredCaptchaCode and captchaId values posted from the frontend
  • Validates captchas by calling the validate(userEnteredCaptchaCode, captchaId) method
  • Returns the json-formatted captcha validation results to frontend
package com.captcha.botdetect.examples.jquery.basic_form; 

import com.captcha.botdetect.web.servlet.SimpleCaptcha; 
import com.google.gson.Gson; 
import com.google.gson.JsonObject; 
import com.google.gson.JsonParser; 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

public class BasicServlet 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 userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString(); 
        String captchaId = formDataObj.get("captchaId").getAsString(); 
        
        // create a captcha instance to be used for the captcha validation 
        SimpleCaptcha captcha = SimpleCaptcha.load(request); 
        // execute the captcha validation 
        boolean isHuman = captcha.validate(userEnteredCaptchaCode, captchaId); 
        
        // create an object that stores the validation result 
        BasicValidationResult validationResult = new BasicValidationResult(); 
        
        if (isHuman == false) { 
            // captcha validation failed 
            validationResult.setSuccess(false); 
            // TODO: consider logging the attempt 
        } else { 
            // captcha validation succeeded 
            validationResult.setSuccess(true); 
        } 
        
        try { 
            // return the json string with the validation result to the frontend 
            out.write(gson.toJson(validationResult)); 
        } catch(Exception ex) { 
            out.write(ex.getMessage()); 
        } finally { 
            out.close(); 
        } 
    } 
} 

class BasicValidationResult { 

    private boolean success; 

    public BasicValidationResult() { 
    } 

    public boolean getSuccess() { 
        return success; 
    } 

    public void setSuccess(boolean success) { 
        this.success = success; 
    } 
} 

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

jQuery-based Frontend and the plain PHP on Backend

This is a partial walk-through of the example source code. It is not meant to replace a proper step-by-step guide. If you are new to BotDetect, skip it for now; and do start your first jQuery captcha integration by following our step-by-step jQuery CAPTCHA Integration Guide.

Introduction

This basic jQuery captcha example shows the minimal code required to display and validate captchas in an application with a jQuery frontend and the plain PHP backend.

Download the BotDetect PHP CAPTCHA Library archive and run this example

Within this page, the root folder of the extracted archive is referred as the <BDC-DIR>

This example is in the <BDC-DIR>/examples/simple-api/simple-api-jquery-captcha-example/ folder; and contains the following files:

Frontend: basic.html

The basic.html source file does the following:

  • Loads the BotDetect CAPTCHA jQuery Plugin into the page
  • Displays the captcha and user-input markups on the page
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <title>BotDetect jQuery CAPTCHA Examples</title> 
  <link href="styles/styles.css" type="text/css" rel="stylesheet"> 
</head> 
<body> 
    <header> 
        <div class="header-content"><h1>BotDetect jQuery CAPTCHA Examples</h1></div> 
    </header> 

    <nav> 
      <ul class="nav"> 
        <li><a href="basic.html" class="active">Basic Example</a></li> 
        <li><a href="contact.html">Contact Example</a></li> 
      </ul> 
    </nav> 

    <section id="main-content"> 
        <form id="basicForm" method="POST"> 
            <div id="form-messages"></div> 

            <!-- captcha challenge: placeholder --> 
            <div id="botdetect-captcha" data-captchastylename="jqueryBasicCaptcha"></div> 

            <label> 
                <span>Retype the characters from the picture:</span> 
                <!-- captcha code: user-input textbox --> 
                <input 
                    type="text" 
                    id="userCaptchaInput" 
                > 
            </label> 

            <button type="submit" id="submitButton">Validate</button> 
        </form> 
    </section> 
    
    <script src="node_modules/jquery/jquery.min.js"></script> 
    <script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script> 
    <script src="js/basic.js"></script> 
</body> 
</html> 

Frontend: basic.js

The js/basic.js source file does the following:

  • Sets the captchaEndpoint property to point to the captcha endpoint path on backend
  • Loads the captcha challenges from backend
  • Sends the post request with the captcha id and the user entered captcha code to backend
  • Processes the captcha validation results:
    • when the captcha validation fails -- it reloads captcha and displays an error message
    • when the captcha validation succeeds -- it executes by the captcha protected action
$(function () { 

    // create the frontend captcha instance in the DOM.ready event-handler; 
    // and set the captchaEndpoint property to point to  
    // the captcha endpoint path on your app's backend 
    var captcha = $('#botdetect-captcha').captcha({ 
        captchaEndpoint: 'botdetect-captcha-lib/simple-botdetect.php' 
    }); 


    // process the form on submit event 
    $('#basicForm').submit(function (event) { 

        // get the user-entered captcha code value to be validated at the backend side         
        var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); 

        // get the id of a captcha instance that the user tried to solve 
        var captchaId = captcha.getCaptchaId(); 

        var postData = { 
            // add the user-entered captcha code value to the post data 
            userEnteredCaptchaCode: userEnteredCaptchaCode, 
            // add the id of a captcha instance to the post data 
            captchaId: captchaId 
        }; 

        // post the captcha data to the backend 
        $.ajax({ 
            method: 'POST', 
            url: 'form/basic.php', 
            dataType: 'json', 
            contentType: 'application/json', 
            data: JSON.stringify(postData), 
            success: function (response) { 
                if (response.success == false) { 
                    // captcha validation failed; show the error message 
                    $('#form-messages') 
                        .removeClass() 
                        .addClass('alert alert-error') 
                        .text('CAPTCHA validation failed.'); 
                    // call the captcha.reloadImage() 
                    // in order to generate a new captcha challenge 
                    captcha.reloadImage(); 
                } else { 
                    // captcha validation succeeded; proceed with the workflow 
                    window.location.replace('notify_page/basic_success_notify.html'); 
                } 
            }, 
            error: function (error) { 
                throw new Error(error); 
            } 
        }); 

        event.preventDefault(); 
    }); 
}); 

Backend: botdetect.xml

The botdetect-captcha-lib/config/botdetect.xml source file contains the following:

  • Captcha style definitions consisting of:
    • The name of a captcha style
    • The ID of an <input> element in which user enters captcha codes
    • Other option settings -- the captcha code length in this particular case
<?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.4.xsd"> 

  <captchaStyles> 
    <captchaStyle> 
      <name>angularBasicCaptcha</name> 
      <userInputID>userCaptchaInput</userInputID> 
      <codeLength>3-5</codeLength> 
    </captchaStyle> 
  </captchaStyles> 
</botdetect> 

Backend: basic.php

The form/basic.php source file does the following:

  • Extracts the $userEnteredCaptchaCode and $captchaId values posted from the frontend
  • Validates captchas by calling the Validate($userEnteredCaptchaCode, $captchaId) method
  • Returns the json-formatted captcha validation results to frontend
<?php header('Content-Type: application/json'); 

if ($_SERVER['REQUEST_METHOD'] === 'POST') { 

  require('../botdetect-captcha-lib/simple-botdetect.php'); 

  $postedData = (array) json_decode(file_get_contents('php://input'), true); 

  $userEnteredCaptchaCode = $postedData['userEnteredCaptchaCode']; 
  $captchaId = $postedData['captchaId']; 

  // create a captcha instance to be used for the captcha validation 
  $captcha = new SimpleCaptcha(); 
  // execute the captcha validation 
  $isHuman = $captcha->Validate($userEnteredCaptchaCode, $captchaId); 

  if ($isHuman == false) { 
    // captcha validation failed 
    $result = array('success' => false); 
    // TODO: consider logging the attempt 
  } else { 
    // captcha validation succeeded 
    $result = array('success' => true); 
  } 

  // return the json string with the validation result to the frontend 
  echo json_encode($result); exit; 
} 

Please Note

The new experimental Simple API is still work-in-progress. This Integration Guide & Examples require you to have the jQuery Captcha Plugin v2.3.0 on frontend, and one of the following BotDetect CAPTCHA releases on backend: ASP.NET v4.4.1+, Java v4.0.Beta3.6+, PHP v4.2.4+.

Current BotDetect Versions