Search code examples
javascriptjquerypreventdefault

Can't use preventDefault() with if, else


$.get in the code below returns a boolean value in JSON format named data. But whether the value of data is false or true preventDefault() prevents the submission of the form anyway.

$(document).ready(function() {
  $("#username").blur(function() {
    let username = document.getElementById("username").value;
    
    $.get("/check", {
      username_value: username
    }, function(data) {
      alert(data);
      
      $("#submit").click(function(e) {
        if (data) {
          e.preventDefault();
        } else if (!data) {
          e.submit();
        }
      });
    });
  });
});

And this is the /check part

@app.route("/check", methods=["GET"])
def check():
    """Return true if username available, else false, in JSON format"""
    get_username = request.args.get("username_value")

    users = db.execute("SELECT username FROM users")

    lenght = len(get_username)
    i = 0
    for user in users:
        if get_username == users[i]["username"] or not lenght > 1:
            return jsonify(True)
        i += 1

    return jsonify(False)

I am very new at coding business btw. Thanks for help.


Solution

  • I solve the problem by replacing the $.get with $.ajax. I guess the problem was about the fact that $.get only works async. So I used $.ajax's async paramater at false. Then it worked just as I want.

    Last version of the code:

    $(document).ready(function() {
              $('#form').submit(function(e){
                  let username = document.getElementById("username").value;
                  let password = document.getElementById("password").value;
                  let confirmation = document.getElementById("confirmation").value;
                  var boolean_data;
                  $.ajax({url: "/check?username=" + username, type: 'get', async: false, success: function(data){boolean_data=data;}});
    
                  if(!boolean_data) {
                    alert("\"" + username + "\"" + " username is already taken.");
                    e.preventDefault();
                  }
                  else if(!password || !confirmation) {
                      alert("Pls povide a password and confrim it");
                      e.preventDefault();
                  }
                  else if(password != confirmation) {
                      alert("Passwords don't match");
                      e.preventDefault();
                  }
    
              });
          });
    

    Thanks to everyone who commented and answered my question.