简体   繁体   中英

Why can't I get the alert to show?

I have been trying to use an alert as a way to tell the user that a given username has already been registered but the alert message isn't displayed.

So, the idea is that on registration the username is sent to python where it will be checked if the username already exists if so the code will return jsonify(False) . Then in javascript, it should display an alert message if the return is false . But my code doesn't work.

Python:

@app.route("/check", methods=["GET"])
def check():
       """Return true if username available, else false, in JSON format"""
username = request.args.get("username")
rows = db.execute("SELECT * FROM users WHERE username = :username", username=username)
if len(rows) >= 1 or len(username) < 1:
    return jsonify(False)
else:
    return jsonify(True)

HTML:

form action="/register" onsubmit="validateUsername()" method="post" id ="register">
        div class="form-group">
            input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
        /div>
        div class="form-group">
            input class="form-control" name="password" placeholder="Password" type="password">
        /div>
        div class="form-group">
            input class="form-control" name="confirmation" placeholder="Confirm Password" type="password">
        /div>
        button class="btn btn-primary" id="submittion" type="submit">Register
    /form>
    script>
       let username = document.querySelector('input[name=username]');
       document.getElementById("submittion").addEventListener("click",function() {
            $.get('/check?username=' + username.value, function(data) {
                if (data==false){
                    data.preventDefault();
                    alert("Username is not available!");
                }
                else {
                   alert("not working");
                }
            });
        });

</script>

When data is submitted, the user should be alerted that the username already exists.

PS: I know I left some of the < out in order to show my HTML code properly.

The ajax request is send on submit, but it doesn't have enough time to receive a response before the form is submitted. To prevent the form from submitting you can use event.preventDefault :

document.getElementById("submittion").addEventListener("click", function(event) {
  event.preventDefault();
  // The ajax call
});

Update

You probably want to listen to form submit event instead of button click (eg for keyboard support). That said, the problem here is that the submit handler needs to "wait" for the async ajax check.

To make this work you could keep track if the user was checked and do a resubmit while disabling the check (untested code below):

const form = document.getElementById("register");
const username = form.querySelector("input[name=username]");
let checkUser = true;

form.addEventListener("submit", function(event) {
  if (checkUser) {
    // Prevent the form from submitting
    event.preventDefault();

    // Check the username
    $.get("/check?username=" + username.value, function (data) {
      if (data === false) {
        alert("Username is not available!");
      } else {
        // Resubmit the form without the user check
        checkUser = false;
        form.submit();
        return;
      }
    });
  }

  // Reset the variable for the next check
  checkUser = true;
});

Alternative

You could also post straight to the /register route (via ajax) and perform the validation/checks there. When everything is ok you can register the the user and return true, otherwise return false when check fails:

form.addEventListener("submit", function(event) {
  // Prevent the form from submitting
  event.preventDefault();

  // Post the form data
  $.post(form.action, form.serialize(), function(data) {
    if (data === false) {
      // Register failed
      alert("Username is not available!");
    } else {
      // Register successfull
      window.location.replace("/welcome");
    }
  });
});

And maybe you can try to avoid JavaScript after all by performing all logic serverside, and render the template with form errors. But that's beyond the scope of this 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