-2

For some reason, the check route does not return false when the username is unavailable. Does anyone have an idea of what I am doing wrong?

I have tried various different notations for the javascript code, but I have not altered the check code because it seems correct to me.

Here is the python code:

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

    username = request.form.get("username")

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

    if not len(str(username)) > 0:
        return jsonify(False)
    for taken_username in taken_usernames:
        if username == taken_username["username"]:
            return jsonify(False)

    return jsonify(True)

Here is the html code using the above route:

{% extends "layout.html" %}

{% block title %}
    Register
{% endblock %}

{% block main %}
    <form action="/register" method="post" onsubmit="function(event) {
                        event.preventDefault();
                    }">
        <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" type="submit">Register</button>
    </form>
{% endblock %}

{% if get_flashed_messages() %}
    <script>

        var username = document.querySelector('input.username');
        var register = document.querySelector('form');
        register.onsubmit = function(success) {
            $.get('/check?username=' + username, function() {
                if (success == false) {
                document.getElement('form').addEventListener("submit", function(event){
                    event.preventDefault();
                    });
                    alert('Username already taken');
                }
                else {
                    register.submit();
                }

            });
        };


    </script>
{% endif %} 

The route is supposed to return "false" when the username is unavailable, but it returns "true".

Franklin Estein
  • 21
  • 1
  • 1
  • 5

1 Answers1

1

If the method is GET, you can access to your data like below:

request.args.get('username', '')

So, you need to replace

username = request.form.get("username")

By

username = request.args.get("username", "")
ASSILI Taher
  • 1,210
  • 2
  • 9
  • 11