I'm working on validating CAPTCHA input using AJAX. I realized I couldn't return a value from the success handler on the AJAX call, so I created a global variable so the success handler and the validation function could talk to eachother. But it's not working in the most mistifying way. First, the code:
jQuery('#contact').submit(function(event) {
if (validate_form())
{
submit_form(event);
}
else
{
return false;
}
});
var valid = true;
function validate_form()
{
valid = true;
// test form stuff here
// if something goes wrong valid will be set to false
if (!valid)
{
alert("form is not valid, refreshing captcha");
// refresh form
// ....
}
else
{
alert("form is valid, checking captcha");
check_recaptcha();
}
alert("finally, form is:" + valid);
return valid;
}
function check_recaptcha()
{
alert("checking captcha now");
// take only recaptcha values from form
var recaptcha_vals = jQuery(':input[name^="recaptcha"]').serialize();
jQuery.post('recaptcha.php', recaptcha_vals, function(data) {
alert("recaptcha post has succeeded!");
if (data == '1\n' /*success!*/)
{
alert("recaptcha is correct!");
jQuery('#recaptcha_error').empty();
}
else
{
alert("recaptcha is incorrect!");
show_recaptcha();
jQuery('#recaptcha_error').html("<p class=\"error\">CAPTCHA was incorrect, please try again.</p>");
valid = false;
}
});
}
I tested this code with nothing in the CAPTCHA input field (an obviously incorrect value). According to the alerts, each part of the code went through as expected, except valid
was still true
after check_recaptcha()
executes, even though I know the "incorrect" branch was followed. So question #1 is: Why isn't the event handler able to set valid
to false
?
Here's where it gets weird. In the above scenario, the form doesn't submit, even though validate_form()
returns true
(according to the alerts). However, when I comment out all the alerts and try it again with the exact same inputs, then the form DOES submit. So question #2 is: What's up with THAT? #1 is more important though.