Function never returning true (JQuery)

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.

You’re making an asynchronous call. You set a value to false, tell JS that you’re making an async call, return the value (which is false). The async call is executed when the JS engine has time, which will be the frame after that

If JS worked like you have written the program, then every call would block until it completed, which would lock the browser every time you made an HTTP call

async function validUsername(username) {
  return await $.ajax({
    // set up call and return true or false
  });
}

Note that this on its own probably won’t completely fix things, but try this first, and then can see where other things need to be adjusted

1 Like

Thank you! That Worked.

1 Like