1

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!

3
  • this should error because you need a + after username='. should be username='+input.value, Commented Feb 28, 2019 at 16:20
  • 2
    let input document.querySelector('username'); is missing an equal sign. Commented Feb 28, 2019 at 16:22
  • Your Javascript contains many syntactical errors; here is the corrected code: jsfiddle.net/a9Lhwbvf Commented Feb 28, 2019 at 16:26

2 Answers 2

5

Your Javascript contains many errors.

First, let input document.querySelector('username') is missing an equal sign, which is necessary when doing variable assignment. Apart from that, your query selector is not correct, as it is looking for a username element (which does not exist). You should be querying the DOM for an input element with the class for control with the name attribute set to "username"; the query selector would be 'input.form-control[name="username"]'. That line should be:

let input = document.querySelector('input.form-control[name="username"]');

See document.querySelector.

Second, you wrote $.get('/check?username=' input.value, which is incorrect; if you want to concatenate two strings, the + operator should be used. That part of the code should be rewritten as:

$.get('/check?username=' + input.value

Third, for the callback function of the jQuery.get, you wrote function(data) [code here] when curly braces are needed for a function expression. The correct code is:

 function(data){   
  //code here
 }

Fourth, you wrote if data == False:. if statements in Javascript have the condition in brackets and the code to execute in curly braces. That should be correctly written as:

if(data === false){
  //do something
}

Lastly, you forgot the end bracket when calling jQuery's $.get. Functions should be called with a start bracket and an end bracket after the function name—i.e., functionName(/*arguments go in here*/). You wrote

$.get(/*<-this bracket is never closed*/ '/check?username=' input.value, function(data)
            if data == False:
            alert("This username is already taken");
            event.preventDefault();

The correct code is:

$.get('/check?username=' + input.value, function(data){
     //do stuff
});

Corrected Code:

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();
         }
   });
}

I suggest you read a Javascript tutorial first before trying to write Javascript. As well, you should always check the console (Ctrl + Shift + I) when you are debugging, as the console will indicate to you any syntax errors (or other errors) and the line(s) at which they occurred.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks alot for the tips! I also saw you wrote false lower case in javascript, would this mean I should pass them to jsonify in the check function as lower case aswell? As python doesn't take this, should I then make it 'true' and 'false'? Or am I on the wrong track here? Also, the code is not yet working, does that mean I need to adjust my 'check' code?
Also document.querySelector('username') should be document.querySelector('input.form-control[name="username"]')
@TimVerlaan I have edited my answer. See if it works for you now.
3

Your code is for sure will gives a lot of errors .. And while you're using jquery you can submit the form like this

$('form').on('submit' , function(e){
  e.preventDefault();  // use it outside `$.get` not inside it
  console.log($('input[name="username"]').val()); // get the username value
  console.log($(this).serialize()); // get form serialize data
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>aA

Additional:

  • to concatenate string in javascript use +

    $.get('/check?username=' + input.value, function(data)

  • Always keep your eyes on console for errors

3 Comments

Thanks for your help! I must admit though I am so new to programming, especially jQuery that I don't understand your method. It took me the afternoon to understand my attempt (with all the faults therein)
You're totally welcome @TimVerlaan .. If you accept my advice -> there're tons of javascript libraries makes life easier .. you can pick up one of them instead of working with pure javascript .. Its up to you at the end .. have a great day :-)
Thanks for the advice, I will look into more libraries! These are litterally my first steps into javascript so probably will be a dumpy road though. Another small question: do you see anything wrong with my python code? I have not been able to get the script to work yet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.