Flask : AJAX with jQuery
In this page, we'll learn how to use AJAX with JQuery via simple example app.
Conventional web applications transmit information to and from the server using synchronous requests, which means we fill out a form, hit submit, and get directed to a new page with new information from the server.
In other words, web application needs to pass in the data from client side to the server side methods to get response from the server. The jQuery is just one simple way to achieve this. We may use other client side libraries or frameworks like AngularJS to POST data to the python web application.
However, with AJAX, when we hit submit the following things happen:
- JavaScript will make a request to the server
- interpret the results
- update the current screen
AXJS(Asynchronous JavaScript and XML) is Asynchronous, so a user can continue to use the application while the client program requests information from the server in the background.
We'll use virtualenvwrapper:
k@laptop:~$ mkvirtualenv venv New python executable in /home/k/Envs/venv1/bin/python Installing setuptools, pip, wheel...done. (venv) k@laptop:~$
Install Flask:
$ pip install Flask ... Successfully installed Flask-0.11.1 Jinja2-2.8 MarkupSafe-0.23 Werkzeug-0.11.11 click-6.6 itsdangerous-0.24
We'll start from the simples app:
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run()
Here is the list of our files used in this tutorial:
We may want to create a Sign Up page called templates/signUp.html using Bootstrap to power our html files:
<!DOCTYPE html> <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=""> <title>SignUp Template for Bootstrap </title> <link href="static/css/bootstrap.min.css" rel="stylesheet"> <link href="static/css/signup.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> </head> <body> <div class="container"> <form class="form-signin" role="form"> <h2 class="form-signin-heading">Please Sign Up</h2> <input type="email" id="inputUsername" name="username" class="form-control" placeholder="Email address" required autofocus> <input type="password" id="inputPassword" 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>
We need to add a python method called signUp to handle the request and render the corresponding html file. We use the render_template to display the signUp page on a /signUp request. We return the rendered template as response:
from flask import Flask, render_template, request, json app = Flask(__name__) @app.route('/') def hello(): return "Hello World!" @app.route('/signUp') def signUp(): return render_template('signUp.html') if __name__=="__main__": app.run()
Now we'll use jQuery AJAX to post the form data to the Python Flask method.
So, let's create a new JavaScript file called signUp.js and include it after jQuery in signUp.html.
<head> ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src="static/js/signUp.js"></script> </head>
In script.js, we'll attach a click event on button click and call python method using jQuery AJAX. We'll have serialized the form data using $form.serialize() and posted it to the python method, /signUpUser:
$(function(){ $('button').click(function(){ var user = $('#inputUsername').val(); var pass = $('#inputPassword').val(); $.ajax({ url: '/signUpUser', data: $('form').serialize(), type: 'POST', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); }); });
Now let's add the python method signUpUser() to receive the data from the client side:
from flask import Flask,render_template, request,json app = Flask(__name__) @app.route('/') def hello(): return "Hello World!" @app.route('/signUp') def signUp(): return render_template('signUp.html') @app.route('/signUpUser', methods=['POST']) def signUpUser(): user = request.form['username']; password = request.form['password']; return json.dumps({'status':'OK','user':user,'pass':password}); if __name__=="__main__": app.run()
Here, in order to retrieve the posted parameters we used of the request module. We have also used json module to return json data to the client side. The json.dumps returns the json to client side.
Now restart the app and point browser to http://localhost:5000/signUp to sign up.
Then, check browser console to see the returned json data:
We can see our python flask jQuery AJAX is up and running!
Files are available from git
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization