5

I am trying to write the script for a form such that if a username is taken, the user is alerted that it is taken, and submission of the form is blocked. If the username then types in the correct password, the script allows the form to be submitted. The script uses $.get() to query a SQL database, returning true to the callback function if the username is available, and false if it is not. I am positive this part of my application works correctly.

Below is my script, with pseudo code entered for the part I cannot solve, as well as the form itself.

<script>
        $(document).ready(function() {
            $("#check").submit(function(event){
                $.get("/check",{username: $("#username").val()} , function(data) {
                    if (data == false){
                        alert("Taken");
                    }
                });
                // if callback returns false ie. data == false, 
                // return false (thus blocking form submission);
                // else if callback returns true, ie. data == true, 
                // return true (thus allowing form submission);
            });
        });
</script>

    <form action="/register" method="post" id="check">
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text" id="username">
        </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" id="register">Register</button>
    </form>

My problem is that I cannot seem to base the behavior of the second function $("#check").submit(function(event), which controls the form's submission on the value returned to the callback function in jQuery.get(), which tells me if the username is taken or not.

Any assistance in how to go about thinking of how to solve this would be really appreciated, and happy to provide clarification as needed.

1

Perhaps revisit the Words example in Lecture 7, which does something similarly using javascript.

https://cs50.harvard.edu/college/weeks/7/notes/#words

In that Words example:

The Python code in application.py uses a jsonify function to return a list as a JSON object:

@app.route("/search")
def search():
    q = request.args.get("q")
    words = [word for word in WORDS if q and word.startswith(q)]
    return jsonify(words)

And our index.html has the JavaScript to append each word as a <li> element:

let input = document.querySelector('input');
input.onkeyup = function() {
    $.get('/search?q=' + input.value, function(data) {
        let html = '';
        for (word of data) {
            html += '<li>' + word + '</li>';
        }
        document.querySelector('ul').innerHTML = html;
    });
};

Per the spec, the route should accept, via GET, an HTTP parameter called username. In the Words example, the parameter was called q

If username is at least 1 char long, then want to query the db to see if it is taken already or not (using a SELECT query, probably). If it is taken, you want check to return false in JSON format (ie, jsonify(false)) If it isn’t taken, ie, it’s available, you should return true

Now, in order to get that variable called username, your HTML register must have some javascript that will call your check route (just like in Words, the javascript calls the /search route) with the username that the user has typed into your form. As the spec suggests, you’ll want to prevent the form from being submitted until you’ve done this check.

You would have done something similar in pset7 (survey problem), where you might have had something like:

document.querySelector('form').onsubmit = function() {

and in that function, you checked if the field(s) were filled out.

This is similar, except rather than just checking if the field was entered, you'd call $.get('/check?username = ... as in the Words example.

2
  • Thanks! So this makes sense but doesn't fully answer my question. I am able to return true or false via the check route, but the problem is that I am unable to get my code to prevent submission if the username is taken, and allow submission if the username is available. Happy to clarify further as needed and thank you again for helping out!
    – RJPQ
    Feb 11 '19 at 11:41
  • I have the same issue. It always log after clicking ok in the pop up window...
    – Jin Chen
    Feb 22 '19 at 15:37
0

You can use .blur to trigger server side check function. I am also stuck in this check implimentation but now my code working.

    <script>
    $("#username").blur(function(){
        $.get("/check", {username: $("#username").val()} , function(data){
            if (data == "false"){
                $("form").submit(function(e){
                    e.preventDefault();
                    alert("Username Exists");
                    location.reload();
                });
            }
        });
    });
</script>
<form action="/register" method="post">
    <div class="form-group">
        <input id="username" 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 (again)" type="password">
    </div>
    <button class="btn btn-primary" type="submit">Register</button>
</form>
0

Probably not the most elegant solution, but I hid the select button if the form wasn't to be submitted, and showed it if it is allowed.

if (data == false){
                    alert("Taken");
                    $("button").hide();
                } else {
                    $("button").show();
                }

You must log in to answer this question.

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