article

Friday, February 21, 2020

jQuery AJAX based Registration System using Python Flask MySQL


jQuery AJAX based Registration System using Python Flask MySQL

Database table
CREATE TABLE `user_test_flask` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NULL,
  `email` varchar(50) NULL,
  `pwd` varchar(255) NULL,
  `admin` tinyint DEFAULT 0,
  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
from flask import Flask, render_template, url_for, request, json, jsonify
from flaskext.mysql import MySQL
import pymysql
from werkzeug import generate_password_hash, check_password_hash

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('/')
def home():
 return render_template('signup_user_flask.html')
 
@app.route('/signup', methods=['POST'])
def signup():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
 
    _json = request.json
    _name = _json['name']
    _email = _json['email']
    _pwd = _json['password']
 
    if _email and _name and _pwd:
 
        cursor.execute('SELECT email FROM user_test_flask WHERE email = %s', (_email))
        user_exist = cursor.fetchone()
  
        if user_exist:
            resp = jsonify({'message' : 'User already registered'})
            resp.status_code = 409
            return resp
        else:
            sql = "INSERT INTO user_test_flask(name, email, pwd) VALUES(%s, %s, %s)"
            data = (_name, _email, generate_password_hash(_pwd),)
            cursor.execute(sql, data)
            conn.commit()
            cursor.close()
            conn.close()
   
            resp = jsonify({'message' : 'User registered successfully'})
            resp.status_code = 201
            return resp
    else:
        resp = jsonify({'message' : 'Bad Request - invalid parameters'})
        resp.status_code = 400
        return resp
  
if __name__ == '__main__':
 app.run(debug=True)
//signup_user_flask.html
<html>
<head>
<title>jQuery AJAX based Registration System using Python Flask MySQL</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
 $('#signupSubmit').on('click', function(e) {
  e.preventDefault();
  $('#loading').show();
  var name = $('#fullname').val();
  var email = $('#email').val();
  var pwd = $('#password').val();
  var cnfpwd = $('#cnfpassword').val();
  
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/i;
  
  if(email != "" && pwd != "" && cnfpwd != "") {
   if(pwd != cnfpwd) {
    $('#msg').html('<span style="color: red;">Password and confirm password must match</span>');
   } else if(!regex.test(email)) {
    $('#msg').html('<span style="color: red;">Invalid email address</span>');
   } else {
    $.ajax({
     method: "POST",
     url: '/signup',
     contentType: 'application/json;charset=UTF-8',
     data: JSON.stringify({'name': name, 'email': email, 'password': pwd}),
     dataType: "json",
     success: function(data) {
      $('#signupform').hide();
      $('#loading').hide();
      $('#msg').html('<span style="color: green;">You are registered successfully</span>');
     },statusCode: {
      400: function() {
       $('#loading').hide();
       $('#msg').html('<span style="color: red;">Bad request parameters</span>');
      },
      409 : function() {
       $('#loading').hide();
       $('#msg').html('<span style="color: red;">You are already registered user</span>');
      }
     },
     error: function(err) {
      console.log(err);
     }
    });
   }
  } else {
   $('#loading').hide();
   $('#msg').html('<span style="color: red;">All fields are required</span>');
  }
 });
});
</script>
</head>
<body>
<h1 align="center">jQuery AJAX based Registration System using Python Flask MySQL</h1>
<div class="reg-box" style="width: 500px; margin: auto;">
  <h4 id='loading' style="display:none;"><img src="{{ url_for('static', filename='img/loader.gif') }}"/> Loading..</h4>
  <div style="clear: both;"></div>
  <div id="msg"></div>
  <div id="signupform" style="width: 500px; margin: auto;">
   <h2>Sign Up</h2>
   <dl>
    <p>
     <input id="fullname" class="form-control" value="" type="text" placeholder="Full Name" required>
    </p>
    <p>
     <input id="email" class="form-control" value="" type="text" placeholder="Email" autocomplete="off" required>
    </p>
    <p>
     <input id="password" class="form-control" value="" type="password" placeholder="Password" autocomplete="off" required>
    </p>
    <p>
     <input id="cnfpassword" class="form-control" value="" type="password" placeholder="Confirm Password" autocomplete="off" required>
    </p>
   <p>
    <input type="button" id="signupSubmit" class="btn-info" value="Submit">
   </p>
   </dl>
   
  </div>
 </div>
<style>
body { font-size:16px;}
.reg-box {
    background: none repeat scroll 0 0 #EEEEEE;
    border: 1px solid #CCCCCC;
    border-radius: 12px 12px 12px 12px;
    margin-top: 20px;
    padding: 10px;
}
.form-control {
    display: block;
    width: 100%;
    height: 34px;
    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;
}
.btn-info {
    color: #fff;    width: 100%;text-align: center;vertical-align: middle;
    background-color: #5bc0de;    border: 1px solid transparent;
    border-color: #46b8da;padding: 6px 12px;font-size: 14px;border-radius: 4px;
}
</style>
</body>
</html>

Related Post