0

I'm trying to use Jquery with Ajax to check if username is available or not, I am checking the code twice, loading image is coming but username messages are not displaying and even loading image is not being hidden.

Help me find what went wrong, please

in Script.js

$(document).ready(function() {
  $("#username").on('input', function(e) {
    $('#msg').hide();
      $('#loading').show();
      if($('#username').val() == null || $('#username').val == ""){
      $('#msg').show();
      $('#msg').html("Username is required field.").css("color", "red");
      $('#loading').hide();
      }
      else{
        $.ajax({
          type: "POST",
          url: "/signup",
          data: $('#RegisterForm').serialize(),
          dataType: "html",
          cache: false,
          success: function(msg) {
           $('#msg').show();
           $('#loading').hide();
           $("#msg").html(msg);
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#msg').show();
            $('#loading').hide();
            $("#msg").html(textStatus + " " + errorThrown);
          }
        });
      }
    });
  });

python in main.py

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    --------
        if request.method == 'POST' and form.validate_on_submit():
            user = User.query.filter_by(username=form.username.data).first()
            if user:
                resp = jsonify('<span style="\'color:red;\'">Username unavailable</span>')
                resp.status_code = 200
                return resp
            else:
                resp = jsonify('<span style="\'color:green;\'">Username available</span>')
                resp.status_code = 200
                return resp
            hashed_password = generate_password_hash(form.password.data, method='sha256')
            new_user = User(username=form.username.data, email=form.email.data, password=hashed_password)
            try:
                ---------
    else:
       -------
    return render_template('signup.html', form=form)

WTForms in html

HTML code

<form class="form-signin" method="POST" action="/signup">
    <h2 class="form-signin-heading">Sign Up</h2>
    {% for field, errors in form.errors.items() %}
      {{ ', '.join(errors) }}
    {% endfor %}
    {{ form.hidden_tag() }}
    {{ wtf.form_field(form.username) }}
    <div id="msg"></div>
    <span id="loading" style="display: none;"><img src="{{ url_for('.static', filename='images/loading.gif') }}"></span>
    {{ wtf.form_field(form.email) }}
    {{ wtf.form_field(form.password) }}
    {{ wtf.form_field(form.cpassword) }}
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
  </form>

</div> 
6
  • did you try to see javascript errors in JavaScript Console in DevTools in Firefox/Chrome Commented Dec 18, 2020 at 0:48
  • did you run server in console/terminal to see all error message? Commented Dec 18, 2020 at 0:48
  • did you use print() to see what you get on server, what you send to server, and which part of code is executed? It is called "print debuging" Commented Dec 18, 2020 at 0:49
  • I see try in your code but .. do you use print() in except to see errors? If you use except: pass then you hide error and you don't know where is the problem. Commented Dec 18, 2020 at 0:51
  • You have if user: ... return resp else: ... return resp which means in this place it will always exit this function and it will never execute code after this if/else - it will never run hashed_password = .... Do you know how works return ? Commented Dec 18, 2020 at 0:54

1 Answer 1

1
  1. Jsonify expects a dictionary.

jsonify({'message':'ok'}) instead of a string

  1. You need on the backend something like that:
# api
@app.route("/check/<username>", methods=["GET"])
def check(username):
    has_username = db.session.query(exists().where(User.username == username)).scalar()
    return jsonify({"exists": has_username})

Then in javascript

$('#username-input-id').on('input', function() {
        $.getJSON( "/check/"+$("#username-input-id").val(), function( data ) {
            $("#check").html("<i class='fa fa-list-alt'></i>");
            if (data['exists'] === true){
              $("#check").html("<i style='color:red;' class='fas fa-exclamation-triangle'></i>");
            }
        })
    });

where #check above is a holder/span to show an icon if username exists. Customise it with your code.

  1. Also, flask-wtf allows you to do

{{ form.email() }}

instead of

{{ wtf.form_field(form.email) }}

if you passed form=form as a variable

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

Comments

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.