I am working on the new /check additional on the Finance problem. I am trying to prevent the register form from being submitted when the username is already taken, is empty, or is just one character. The /register python code is already working, so these insertions will never be allowed, just trying to prevent the form from being submitted now.
I think my jQuery code is correct, it is the following:
<script>
let input = document.querySelector('input.form-control[name="username"]');
document.querySelector('form').onsubmit = function(event) {
$.get('/check?username=' + input.value, function(data){
if(data === false){
alert("This username is already taken");
event.preventDefault();
}
});
}
</script>
is it located above this HTML code:
<form action="/register" method="post">
<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="Password" type="password">
</div>
<button class="btn btn-primary" type="submit">Register</button>
</form>
However, it does not seem to be talking correctly to my python code. I was thinking maybe a problem in the JSON data I am sending back? I just can't figure it out. Would someone please help me?
@app.route("/check", methods=["GET"])
def check():
"""Return true if username available, else false, in JSON format"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "GET":
username = request.args.get("username")
usernames = db.execute("SELECT username FROM users")[0][username]
if username is not None and len(username) > 1:
if username not in usernames:
return jsonify(True)
else:
return jsonify(False)
else:
return jsonify(False)