I have a small jQuery/AJAX script that checks if a username is already in use or not. It queries a PHP script, which in turn outputs the number of users with the specified username. I have an error counter that keeps track of the number of validation errors on the form, and I increment the counter if the username is already in use.
//Keep track of number of errors
var errors = 0;
//Keep track of error messages
var errorMsg = "";
//Check if the passwords match (this part works as expected)
if($("#password").val() != $("#repeat").val()) {
errors++;
errorMsg += "<li>Passwords do not match!</li>";
}
//Now check if the user exists
var userName = $("#user").val();
$.ajax({
type: "POST",
data : {'user': userName},
cache: false,
url: "js/ajax/addUser.php?action=checkuser",
success: function(data){
var result = parseInt(data);
//For debugging purposes
alert("Before checking the data, # of errors is: " + errors);
if(result > 0) {
errors++;
errorMsg += "<li>A user with the name <strong>" + userName + "</strong> already exists!</li>";
}
//For debugging purposes
alert("After checking the data, # of errors is: " + errors);
}
});
//For debugging purposes
alert("Before validating the form, # of errors is: " + errors);
if(errors > 0) {
//Output error message
}
else {
//Send the form
}
As mentioned in the comments, I have a few alert()‘s for debugging. The first two (within the AJAX request) display the correct amount of errors. However, when I get to the third one, it completely disregards any errors that occurred within the AJAX request.
I have trimmed my code down to just the essentials, but if the error is not clear within the snippet provided, I can post the entire thing.
ajax is asynchronous. Place your logic inside the success.