Search This Blog

Tuesday, November 18, 2008

Classic ASP CAPTCHA with JQuery Cross domain AJAX

It come to the point that i need to maintain my old application which written in ASP. I was asked to add a new feature in form submission to prevent from spamming. CAPTCHA is the thing that i could thought of. Thanks Emir Tüzül who willing to share his ASP CAPTCHA. You can download it from http://www.tipstricks.org/ .

I downloaded the code and modify the code so that the security checking is before the asp postback. The solution i could thought of is AJAX. When i thought of javascript, the coolest javascript framework will be JQuery.

The decision is go for JQuery in order to perform Ajax with ASP.

There is one concern, the application will need to perform cross domain ajax. If use normal jquery ajax (code below), it will work if all the file reside in the same domain but not when cross domain. Error : Exception... "'Permission denied to call method XMLHttpRequest.open' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location: "" data: no] will be displayed.

var html = $.ajax({
url: "/captcha.asp?validateCaptchaCode=" + $("#captchacode").val(),
async: false
}).responseText;

In our case, the file put in different domain. The technics will be use is Cross-Domain getJSON (using JSONP). Sample code below

$.getJSON("captcha.asp?validateCaptchaCode=" + $("#captchacode").val() + "&format=json&jsoncallback=?", function(data)
{
if (data.status == "1")
{ alert("verified and submit.");
$("#form").submit();
result = true;
}
else
{
if (data.session == "0")
RefreshImage("imgCaptcha");
alert("Please key in the security key correctly!");
$("#captchacode").focus();
result = false;
}
});


The Cross-Domain getJSON will espect the data return in Json format. So, my ajax handler file (in my case is captcha.asp) will need to return Json format data for processing.

After develop and tested. It's work. You can download my sample file here and test on it. Please let me know if it's help.

2 comments:

Anonymous said...

Thnx.

Hermund said...

Thank you very much!