Since the validation call is asynchronous, mark that as synchronous by doing:
async: false
[optional] and to prevent form submit default functionality, do:
e.preventDefault();
on submit button click. After doing validation you'll get response based on that response, you can allow form to submit or not.
Simple Code Snippet:
$("#form-submit").on('submit', function(){
var errorMsg = 'Please provide your correct information.';
$(".errorMsg ").text("");
var txtName = $("input#txtName").val();
var responseStatus = false;
var userData = {
'name' : txtName
};
$.ajax({
type: 'POST',
url: '/validate-data',
async: false,
data: userData,
success: function(result){
if(result.status === true){
responseStatus = true;
} else {
responseStatus = false;
errorMsg = result.message;
$(".errorMsg ").text(errorMsg);
return false;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Oops! Something went wrong. Please try again.'); return false;
}
});
if(responseStatus === false){
return false;
} else {
return true;
}
});
See, if that helps.