I have a function that makes an ajax call to check if the username already exists in the database or not. Here is that function :
function isValidUsername(username){
let result =false;
$.ajax({
url: "./UserController",
data: "cmd=checkUsername&username="+username,
success: function(response){
if(response.includes("Valid"))
result = true;
else
result = false;
}
});
return result;
}
I am using Java Servlet to handle the request and code that gets triggered by this request is :
String username = request.getParameter("username");
if(userDAO.getUser(username)!=null)
out.write("Username Exists");
else
out.write("Valid Username");
And I am using isValidUserName() function inside the block of code that is responsible for submitting the signup form :
$(document).on("submit", "#signupForm", function (event) {
var $form = $(this);
if ($("#signupForm .user_gender").val() == null) {
$("#snackbar").html("Select a gender");
showToast();
return false;
}
showLoading();
if(isValidUsername($("#signupForm .user_id").val())){
$.post($form.attr("action"), $form.serialize(), function (response) {
hideLoading();
console.log(response);
$form.trigger("reset");
if (response.includes("Created")) {
location.reload();
}
});
}else{
$("#snackbar").html("Username Already Exists");
showToast();
}
event.preventDefault();
});
For some reason isValidUsername()
is not returning true even though servlet is returning correct result (confirmed it by XHR object returned by servlet). I don’t understand why this is happening.