Q:

Validate Captcha in JSP Page using AJAX

Trying to Use Captcha in my JSP page as below
<%@ page import="net.tanesha.recaptcha.ReCaptcha" %>
<%@ page import="net.tanesha.recaptcha.ReCaptchaFactory" %>
<html>
<head>
<title>Sample Application JSP Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>

<body bgcolor=white>
<form action="CaptchaServlet">
<table border="0" cellpadding="10">
<tr>
<td width="10" align="center" height="10">
<img src="SimpleServletPath">
</td>
<td>
<h1>Sample Application JSP Page</h1>
</td>
</tr>
<tr>
<td>
Please Enter your Comments
<p>
<%
ReCaptcha c = ReCaptchaFactory.newReCaptcha   
("6LdlHOsSAAAAAM8ypy8W2KXvgMtY2dFsiQT3HVq-    ", "6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY", false);
out.print(c.createRecaptchaHtml(null, null));
%>
<INPUT TYPE="TEXT" NAME="text1">
<input type="submit" value="submit" />
</p>  
</td>
</tr>
</table>

</form>
</body>
</html> 

The servlet is as follows
protected void doGet(HttpServletRequest request, HttpServletResponse  response) throws ServletException, IOException {

    String remoteAddr = request.getRemoteAddr();
    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPrivateKey("6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY");

    String challenge = request.getParameter("recaptcha_challenge_field");
    String uresponse = request.getParameter("recaptcha_response_field");
    ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
    PrintWriter out= response.getWriter();
    if (reCaptchaResponse.isValid()) {
        String user = request.getParameter("user");
        out.write("CAPTCHA Validation Success! User "+user+" registered.");
    } else {
        out.write("CAPTCHA Validation Failed! Try Again.");
    }   
}

This works good, but the JSP page gets refreshed when submit value is clicked. How can we pass the Captcha values to Servlet using AJAX and return a value that the Capcha is valid or not without refreshing the page.

A:

Here is the strategy.
Have your submit tracked by a javascript method. That method will send the captcha data to the server. and on sucesss or error the javascript will update the dom with the error message sent by the server/Servlet.
Follow this link https://gist.github.com/madan712/4972634.
In the link above it uses another jsp to validate ( working like a servlet) but you can give the url mapping name there in the url:[your_servlet_path]

