I have already covered an introductory article on getting started with python web application development using Python Flask and MySQL. In this Python Flask jQuery AJAX tutorial, we’ll focus on the client side of the web application. We’ll see how to use jQuery AJAX along with Python Flask web application.
Prior to getting started with this tutorial, make sure you have Python installed. You can check if it’s installed from the command prompt:
python --version
If python is installed, it’ll show the version of python installed.
We’ll use pip to install Flask. Setting up Flask using pip is quite easy.
pip install Flask
Why Python Flask jQuery AJAX ?
Why do we need to use jQuery AJAX along with a python web application ? When creating a web application it’s often needed to pass in the data from client side to the server side methods to get response from the server. jQuery is just one simple way to achieve this. You can also use other client side libraries or frameworks like AngularJS to POST data to the python web application.
Python Flask Web Application
Create a app directory called FlaskApp, navigate to it and create app.py with the following code:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Welcome to Python Flask!"
if __name__ == "__main__":
app.run()
The python code shown above is quite self explanatory.
First we imported the Flask module and then created a flask app instance. We have also defined a hello function with a route defined as / .
Save the app.py and from terminal run:
python app.py
Your app must be now running. Point your browser to http://127.0.0.1:5000/ and you should see the welcome message.
Let’s create a Sign Up page called signUp,html. We’ll be using Bootstrap to power our html files. Here is how _signUp.html_looks like:
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Signin Template for Bootstrap title>
<link href="static/css/bootstrap.min.css" rel="stylesheet">
<link href="static/css/signin.css" rel="stylesheet">
<script src="static/js/jquery-1.9.0.js"> script>
head>
<body>
<div class="container">
<form class="form-signin" action="/signUp" method="post" role="form">
<h2 class="form-signin-heading">Please Sign Up h2>
<input type="email" name="username" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="button">Register button>
form>
div>
body>
html>
Next add a method called signUp on the python side to handle the request and render the corresponding html file. We have used the render_template to display the signUp page on a /signUp request. All we need to do is _import render_template_and return the rendered template as response. Here is how it looks like
from flask import render_template
@app.route('/signUp')
def signUp():
return render_template('signUp.html')
Using Python Flask jQuery AJAX Together
Now we’ll use jQuery AJAX to post the form data to the Python Flask method. Create a new JavaScript file called _script.js_and include it after jQuery in signUp.html.
We’ll attach a click event on button click and call python method using jQuery AJAX. Here is how the script.js looks like:
$(function() {
$('button').click(function() {
$.ajax({
url: '/signUpUser',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
});
In the above code we have simple serialized the form data using $form.serialize() and posted it to the python web method. Now add a python method called signUpUser to receive the data from client side. Here is how it looks like:
@app.route('/signUpUser', methods=['POST'])
def signUpUser():
user = request.form['username'];
password = request.form['password'];
return json.dumps({'status':'OK','user':user,'pass':password});
We have explicitly defined the method that it supports using the methods attribute. In order to retrieve the posted parameters we have made use of the request module. We have also used json module to return json data to the client side. json.dumps returns the json to client side.
Now restart the server and point your browser to http://localhost:5000/ and try to sign up. Check browser console to see the returned json data. So, python flask jQuery AJAX is up and running :)
Wrapping It Up
In this Python Flask jQuery AJAX tutorial, we saw how to post data using jQuery AJAX to a python web application. Do let us know your thoughts, suggestions or corrections in the comments below.
Read : How to Read Email From Gmail Using Python
The code from the above tutorial is available in GitHub.