i am trying to validate a form before adding the visitor info to a mysql db. The jQuery script follows:
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
return false;
}
//Captcha validation
var security_code = $("input#security_code").val();
$.ajaxSetup({cache: false})
$.get('getsession.php', {requested: 'seccode'}, function (data) {
var session = data;
if (security_code !== session) {
$("label#security_code_error").show();
$("input#security_code").focus();
alert ('NO MATCH: '+security_code+' '+session);
return false; // <= FUNCTION SHOULD EXIT HERE
} else {
alert ('MATCH!!!: '+security_code+' '+session);
}
});
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
If a name is missing, then the form displays an error and focus the field to be completed. The problem is the captcha validation. If it matches, the form is successfully processed and the lead gets added to the DB, however, if the security code entered in a text filed does not match the generated code, the error is displayed but the form info is still added to the DB. Looks like the “return false; // <= FUNCTION SHOULD EXIT HERE” is not recognized.
Any suggestion on what is wrong with my code?
The
return falsethat you expect to end your execution is in the callback function for an AJAX request. The first A in AJAX stands for asynchronous, so that function isn’t executed until the request returns a successful response.However, since it is asynchronous, the rest of the function making that AJAX request will still execute, therefore submitting a separate AJAX POST request to submit the form data, completely unrelated to the first AJAX call.
What you need to do is move the below part of your code into the callback function for the AJAX request that checks the captcha, and only execute it if the validation was successful.
The entire code would look like this: