TL;DR => what is wrong with the code in the bottom code-box.
I am trying to call a function called 'check' that will check whether the username filled in is not empty and doesn't already exists in my database. This check function looks as follows:
@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 * 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)
I don't know whether this code is working as it is, but I think I can make this work. The problem is my inexperience with jQuery. To start I have this rather straightforward HTML code setting up a register page:
<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>
{% endblock %}
I now want to use jQuery to get called when the form is attempted to be submitted in order to check if the username already exists. If it doesn't, the check function should send back 'true' in JSON format. After which the form should be submitted. If it does already exist, I want to send alert message saying 'This username is already taken' and I want to prevent the form from being submitted. Here is my attempt in jQuery, could someone tell me what is wrong with it?
{% block main %}
<script>
let input document.querySelector('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>
Thanks!
+afterusername='. should beusername='+input.value,let input document.querySelector('username');is missing an equal sign.