I have some javascript validation where I check (among other things) if an email is taken, but I can’t get it to work.
function validateField(input) {
errors = false;
messages = ''; //
/* Begin checks */
if (input.hasClass('jEmailUnique')) {
message = 'Email not taken';
$.post('../ajax/j_validate.php', {
step: 1,
email: input.val()
}, function(response){
if (response != '0') {
message = tipInvalid + message;
errors = true;
}
else {
message = tipValid + message;
}
messages += "<p>" + message + "</p>";
});
}
/* End checks */
if (errors == true) {
input.addClass('jHasError').removeClass('jNoError');
}
else {
input.addClass('jNoError').removeClass('jHasError');
}
setTip(input, messages); // show pop up window with error messages
}
Am I losing the scope of messages in the anonymous function in the post or something?
You’re not, but you’re still doing it wrong. Your
messagesvariable is global. Tack avarin front of it to scope it to its function.You also need to call
setTip(input, messages)in the callback, before then,messagesisundefined.