article

Friday, February 21, 2020

Check Availability username with Python Flask Jquery AJAX, MySQL


Check Availability username with Python Flask Jquery AJAX, MySQL

#app.py
from flask import Flask, render_template, url_for, request, json, jsonify
from flaskext.mysql import MySQL
import pymysql

app = Flask(__name__)

mysql = MySQL()
 
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
 
@app.route('/user_check', methods=['POST'])
def username_check():
 conn = None
 cursor = None
 try:
  username = request.form['username']
  
  # validate the received values
  if username and request.method == 'POST':  
   conn = mysql.connect()
   cursor = conn.cursor(pymysql.cursors.DictCursor)
   
   cursor.execute("SELECT * FROM user_test_flask WHERE username=%s", username)
   row = cursor.fetchone()
   
   if row:
    resp = jsonify('Username unavailable')
    resp.status_code = 200
    return resp
   else:
    resp = jsonify('Username available')
    resp.status_code = 200
    return resp
  else:
   resp = jsonify('Username is required field.')
   resp.status_code = 200
   return resp
 except Exception as e:
  print(e)
 finally:
  cursor.close() 
  conn.close()
  
@app.route('/')
def home():
 return render_template('username.html')
 
  
if __name__ == '__main__':
 app.run(debug=True)
//username.html
<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>Check Availability username with Python Flask Jquery AJAX, MySQL</title>
 <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
 <div style="margin: 10px 0 0 10px;width: 600px">
  <h3>Check Availability username with Python Flask Jquery AJAX, MySQL</h3>
  
  <form id="signupform" style="padding: 10px;">
   <fieldset>
    <legend>Check username</legend>
    <div>
     <p style="padding-bottom:5px;font-weight:bold;">Username</p>
     <input type="text" class="form-control" name="username" id="username" autocomplete="off"/>
     <div id="msg"></div>
     <h4 id='loading' style="display:none;"><img src="{{ url_for('static', filename='img/loader.gif') }}"/> Loading..</h4>
    </div>
   </fieldset>
  </form>
 </div>
 <script type="text/javascript">
  $(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");
    } else {
     $.ajax({
      type: "POST",
      url: "/user_check",
      data: $('#signupform').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);
      }
     });
    }
   });
  });
 </script>
<style>
body {font-size:16px;}
#msg {font-weight:bold;padding:10px;}
.form-control {
    display: block;
    width:300px;
    height: 25px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    background-color: #fff;
    background-image: none;
    border: 1px solid #ccc;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
</style> 
</body>
</html>

Related Post