0

I've been banging my head on writing check().

My request.args.get() is returning None and therefore unable to query the username in my javascript.

Here's a screenshot of my console:

Console

I'm expecting: GET /check?username=sam but getting GET /check?username=

The alert box 'Username is taken' appears for existing users and new users. Below is an example of existing user. You can see in the Javascript console that the name is undefined and data is empty.

Existing User

Also, I was having a hard time using $.get() so decided to use $.ajax() instead. I also still have to add the preventDefault.

Any help in the right direction would be greatly appreciated.

Here is my code:

check()

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

    q=request.args.get("username")
    print(f"this is q {q}")

    # get all the usernames from the database
    username = db.execute("SELECT username FROM users WHERE username = :username", username=q)
    print(f"this is user: {username}")

    return jsonify(username)

register.html

{% extends "layout.html" %}

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

{% block main %}
    <form id="registerform" action="/register" method="post" >
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" id="username" 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" id="submitbutton" type="submit">Register</button>
    </form>

    <script>
        var username = document.getElementById('username').value;
        //console.log("this is username1: " + username);

        document.querySelector("form").onsubmit = function() {
            $.ajax({
                    url: "/check?username=" + username,
                    type: "GET",
                    success: function (data){
                        console.log("this is data1: " + data);
                        if (data == false) {
                            console.log("this is False: " + username.value);
                            console.log("this is data: " + data);
                            alert("The Username is taken!");
                            return false;
                        }
                        else {
                            console.log("this is data2: " + data);
                            console.log("this is username True: " + username.value);
                        }
                    //*check for the value returned by the request which is stored in the data argument
                    //which the success function takes, you're returning true or false so check if data==true or false here*
                    },
                    error: function (error) {
                        alert(error);
                    //*Or console.log(error) and check your web console for the error*
                    }
                });
            };


    </script>
{% endblock %}

register()

@app.route("/register", methods=["GET", "POST"])
@app.route("/check", methods=["GET"])
def register():
    """Register user"""
    # if a post then get the username, password and password confirmation
    if request.method == "POST":
        username = request.form.get("username")
        userpwd = request.form.get("password")
        userpwd_confirmation = request.form.get("confirmation")

        # if user didn't enter their username, password and password confirmation the throw an error
        if not username and not userpwd and not userpwd_confirmation:
            return apology("You must enter all fields in Registration")
        # else if the password and password confirmation don't match then throw an error
        elif userpwd != userpwd_confirmation:
            return apology("The passwords must match!")

        if len(username) > 1:
             # call the check function which checks if username is available
            check()

            # generate a password hash
            salt = generate_password_hash(userpwd)

            # get the result of the insert
            result = db.execute("INSERT INTO users(username, hash) VALUES(:username, :hash)",
                        username=request.form.get("username"), hash=salt)
            # if there is no result, that means user is already in database,  then throw an error
            if not result:
                return apology("Username is already in use")

            # Get all from users werhe the username is the username entered (returns a list of dictionaries)
            rows = db.execute("SELECT * FROM users where username = :username ", username=request.form.get("username"))

            # store the session id
            session["user_id"] = rows[0]["id"]

            # redirect user to homepage
            return redirect("/")

        else:
            return apology("Username is too short", 400)
    else:
        return render_template("register.html")
1

document.getElementById('username') may be evaluated in the outer script (as its value should not change), but the .value part should be evaluated when the user tries to submit the form, just before you $.ajax or equivalent.

Personally, as you already pass a settings object to $.ajax, I prefer data: {username: username} for passing arguments, this also encodes them correctly (see encodeURIComponent for doing that yourself).

check should return a jsonified boolean, not a jsonified string.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .