简体   繁体   中英

Validating captcha code using jquery

I have an application form in which i need to validate captcha using jquery. If the captcha entered is wrong then an alert box as to displayed please enter captcha again the entered captcha is wrong.. How can I do this using jquery ?? Please help me. I'm new to jquery.

Here is the code :

$(function() {
    $("#XISubmit").click(function(){
        event.preventDefault()
        val=$('#vercode').val()
        $.ajax({
            type:"post",
            url:"verify-captcha.php",
            data:{'code':val},
            success:function(data){
               if(data=='false'){
                    alert('Re-enter Captcha, You Entered wrong captcha code')
                    $("#cap").html("<img  src='captcha_image.php'>"); }
                else{  
                     document.getElementById("XIForm").submit();
                }
            }

        });    
    });
});

            document.getElementById("XIForm").submit();

                });
Html page :

<label>Security Validation</label>    

<span><img   src="captcha.php"></span><input type="text" name="vercode" id="vercode" size="10" style="margin-top: -1px; float: left; width: 115px; margin-right: 12px;"></li><div id="msg"></div>
captcha.php

<?php
session_start();
$ranStr = md5(microtime());
$ranStr = substr($ranStr, 0, 6);
$_SESSION['cap_code'] = $ranStr;
$newImage = imagecreatefromjpeg("cap_bg.jpg");
$txtColor = imagecolorallocate($newImage, 0, 0, 0);
imagestring($newImage, 5, 5, 5, $ranStr, $txtColor);
header("Content-type: image/jpeg");
imagejpeg($newImage);
?>
verify-captcha.php

<?php
session_start(); 
if ($_POST["code"] != $_SESSION["cap_code"] || $_SESSION["cap_code"]=='')  { 
 echo 'false';
}else{
echo 'true';}

Download recaptcha.jar from https://code.google.com/p/recaptcha4j/downloads/list

<%@ page import="net.tanesha.recaptcha.ReCaptcha" %>
<%@ page import="net.tanesha.recaptcha.ReCaptchaFactory" %>

<form action="." method="post">
    <div class="loginbox">
            <c:set var="PUBLIC_KEY" scope="page" value="${requestScope.properties.get('PUBLIC_KEY')}" />
            <c:set var="PRIVATE_KEY" scope="page" value="${requestScope.properties.get('PRIVATE_KEY')}" />

            <% ReCaptcha c = ReCaptchaFactory.newSecureReCaptcha((String)pageContext.getAttribute("PUBLIC_KEY"), (String)pageContext.getAttribute("PRIVATE_KEY"), false);
                out.print(c.createRecaptchaHtml("errorMessage","blackglass", 2)); %>                        
            <button type="submit">Submit</button>           
    </div>
</form>

Keep the PUBLIC and PRIVATE key in the *.properties file (if not create one) and use ${requestScope.properties.get('PUBLIC_KEY')} to get the PUBLIC and PRIVATE KEY.

Now ajax call below with 2 below parameters. And verify the recaptchaResponseField and recaptchaChallengeField at backend.

recaptchaResponseField=$("input[name=recaptcha_response_field]").val(); recaptchaChallengeField=$("input[name=recaptcha_challenge_field]").val();

var ajax=$.ajax({
            url: API.get_api_url('your_auth_url'),
            data: {recaptchaResponseField:recaptchaResponseField,recaptchaChallengeField:recaptchaChallengeField},
            type: 'POST',
            success: function(data, status, xhr){
                if(data){
                    if(data.statusCode == 0){
                        log("if successfully authenticated.. send to home page");
                    }
                }
            }
        });

At java (backend). use below to validate re-captcha

public boolean isValidCapctha(HttpServletRequest request, String recaptchaResponseField, String recaptchaChallengeField) {  
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(properties.getProperty("PRIVATE_KEY"));
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, recaptchaChallengeField, recaptchaResponseField);
        return reCaptchaResponse.isValid();     
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM