Ok, if somebody could take a look at this, I’d really appreciate it. I’m implementing a captcha in an html form. The captcha is php based, so i need to use jquery to post the submitted form to the captcha check script.
The php script returns 1 if the check was correct, or 0 if it was incorrect.
This is all working great, the problems i am having are with actually submitting the form, or preventing it based on what the php script returns. My the code is as follows:
<form id="contactform" action="FormHandler.cgi" method="POST">
<input name="requiredContact" size="25" type="text" />
<input name="requiredEmailFrom" size="25" type="text" />
<input name="requiredTelephone" size="18" tabindex="3" />
<textarea cols="25" name="comments" rows="4"></textarea>
<select length="2" name="requiredContactMethod" tabindex="5">
<option selected="" value="Email">Email</option>
<option value="Telephone">Telephone</option>
</select>
<img src="captcha/captcha.php" style="float:none; margin:0px 0px -8px 0px; height:26px;"></img>
<input type="text" id="CAPTCHA" style="margin-left: -5px; height:26px;">
<p id="caperror"></p>
<p><input name="B1" type="submit" value="Submit" />
<input name="B2" type="reset" value="Clear" /></p>
</form>
<script>
$('#contactform').submit(function(){
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
data: cap,
dataType: "text",
error: postfail,
success: success
});
return false; //Temporary, to stop the form no matter what.
});
function success(result){
if(result == 1){
alert('was correct');
return true;
}
else{
alert("error" + result);
return false;
}
}
function postfail(){
alert('post failed');
return false;
}
</script>
So what i would like to happen, is when my success function returns false, it stops the form from submitting. If it returns true, go ahead and submit the form. This is what I would like
$('#contactform').submit(function(){
//The ajax post here
//check the value of the ajax success function here;
if(success(result)) {
return true;
}
else {
return false;
}
});
I am not good with function scopes in javascript. If I define a variable inside the success function, I can’t check the value in the form submit function, because it only has a local scope. I could just use a link to submit the form, and then call submit(); but I want the form to be accessible to those without java.
Is there any way to get the ajax post success function’s result back to the scope of the submit() handler?
Unless I’m missing something, you should be submitting the form in the AJAX call’s success function. The AJAX call should also not be being thrown upon form submit. The form should not be being submitted in any way until the check has come back true. IE:
As far as “scoping” goes, this shouldn’t be a “scoping” issue. Let me know if you need further instruction.