Python Flask AJAX WITH JQUERY and JSON | Sign Up using MySQLdb Database
Database Table
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`password` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Sing-up method in app.py
from flask import Flask, render_template, request, url_for, json
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = "caircocoders-ednalan-2020"
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flaskdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/signUp',methods=['POST','GET'])
def signUp():
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
# validate the received values
if _name and _email and _password:
# All Good, let's call MySQL
cur = mysql.connection.cursor()
_hashed_password = generate_password_hash(_password)
cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)",(_name,_email,_hashed_password,))
data = cur.fetchall()
if len(data) is 0:
mysql.connection.commit()
return json.dumps({'message':'User created successfully !'}) #json.dumps() takes in a json object and returns a string.
else:
return json.dumps({'error':str(data[0])})
else:
x = '{ "html":"Enter the required fields"}'
y = json.loads(x) #json.loads() takes in a string and returns a json object.
return y["html"]
if __name__ == '__main__':
app.run(debug=True)
Sign-up page - signUp.html
We may want to create a Sign Up page called templates/signUp.html using Bootstrap to power our html files:
we'll use jQuery AJAX to post the form data to the Python Flask method.
JavaScript file called signUp.js and include it after jQuery in signUp.html.
//templates/signup.html <!DOCTYPE html> <html lang="en"> <head> <title>Python Flask AJAX WITH JQUERY and JSON | Sign Up using MySQLdb Database</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="/static/js/signUp.js"></script> </head> <body> <div class="container"> <div class="header"> <nav> <ul class="nav nav-pills pull-right"> <li role="presentation" ><a href="/">Home</a></li> <li role="presentation"><a href="/showSignin">Sign In</a></li> <li role="presentation" class="active"><a href="showSignUp">Sign Up</a></li> </ul> </nav> <img src="/static/images/Flask_Icon.png" alt="Flask_Icon.png"/ > </div> <div> <h1>Python Flask AJAX WITH JQUERY and JSON</h1> <div id="message"></div> <form class="form-signin"> <p><label for="inputName" class="sr-only">Name</label> <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus></p> <p><label for="inputEmail" class="sr-only">Email address</label> <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus></p> <p><label for="inputPassword" class="sr-only">Password</label> <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required></p> <p><button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button></p> </form> </div> <footer class="footer"> <p>©youtube.com/cairocoders</p> </footer> </div> </body> </html>
//static/js/signUp.js $(function() { $('#btnSignUp').click(function() { $.ajax({ url: '/signUp', data: $('form').serialize(), type: 'POST', success: function(response) { console.log(response); $('#message').html(response); }, error: function(error) { console.log(error); $('#message').html(error); } }); }); });