简体   繁体   中英

Validate form using Flask, Ajax and jQuery to check data from back-end before submitting the form

I have recently started learning Python and jQuery. I am doing a small exercise for validating the form from back-end. I do not want to submit the form if the validation fails.

Here, I want to print the message, user already exists if user record is present in the backend. The code I wrote for validation works but by form is always getting submitted. Much appreciate guidance from this forum on how to handle this form submission.

Here's a snippet of my code: HTML:

<form action="/register" method="post">
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="username" id="user" placeholder="Username*" type="text" required>
        </div>
        <div class="form-group">
            <input class="form-control" name="password" placeholder="Password*" type="password" required>
        </div>



$('form').on('submit', function(e) {
            let user = document.querySelector("#user").value;
            $.get('/validate?q=' + user, function(users) {
                let text = '';
                if (users.length != 0) {
                    document.querySelector("#error").innerHTML = "Username already exists";
                    return false;
                }
            });
        });

application.py

@app.route("/validate")
def validate():
    user = request.args.get("q")
    row = db.execute("SELECT username FROM users WHERE username = ?", user)
    print(row)
    return jsonify(row)

You need to validate that outside your "get" function, preferably using a variable.

$('form').on('submit', function(e) {
        var chkUser = 0;
        let user = document.querySelector("#user").value;
        $.get('/validate?q=' + user, function(users) {
            let text = '';
            chkUser = users.length;
            if (users.length != 0) {
                document.querySelector("#error").innerHTML = "Username already exists";
                return false;
            }
        });
        if (chkUser > 0)
            return false;
    });

I haven't tested this code. Also you should mention how are you subtmitting your form. The easiest way is just to have an <input type='submit'> element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM