简体   繁体   中英

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.

Try change to capture the event from form ID instead of button this way:

$("#form").submit(function (e) {
  if (!data) {
    e.preventDefault();    
  } else {
    e.submit();
  }
});

e.submit() must be used in event from a submited form.

Make sure data is boolean type. and don't forget change the selector to your form ID.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM