As part of a form’s validation process, I’m trying to check if the value entered into one of my text boxes already exists within the database.
My submit function calls a second validation function that uses an ajax call to return the matching number of lines within the DB. If the number of lines equals 0, I want to return a value of true. If the number of lines equals 1+, I want to return a value of false.
As the ajax call runs asynchronous, I only ever get true returned as the function completes before the ajax call is complete.
Reading the web I understand I need to use callbacks but can work out what to do/how to restructure my code.
Submit button function
(function() {
$('#NewBookSave').on('click', function(e) {
e.preventDefault();
var newNameValidationResult = newNameValidation();
alert("Validation = " + newNameValidationResult);
// if validation = true submit form data.....
});
}());
Validation Function
function newNameValidation() {
var newNameValue = $("#NewName").val();
var nameCount;
var isFormValid = true;
$.ajax({
type: "POST",
url: "data_process.php",
data: {
dataDisplayType: 3,
newNameValue: newNameValue
},
success: function(data) {
nameCount = data;
},
complete: function() {
if (nameCount >= 1) {
showErrorMessage(newNameValue, "Error message");
isFormValid = false;
}
}
});
return isFormValid;
};