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>
DevToolsin Firefox/Chromeprint()to see what you get on server, what you send to server, and which part of code is executed? It is called"print debuging"tryin your code but .. do you useprint()inexceptto see errors? If you useexcept: passthen you hide error and you don't know where is the problem.if user: ... return resp else: ... return respwhich means in this place it will always exit this function and it will never execute code after thisif/else- it will never runhashed_password = .... Do you know how worksreturn?