How to Use AJAX with Python Flask

Ayumi Tanaka
5 min readFeb 7, 2021
Photo by Dlanor S on Unsplash

In this article, I will show how to use AJAX with Flask, a Python framework, to receive and display the values entered in a form asynchronously. I added the source code that we need at the end of the article.

What is AJAX?

AJAX stands for “Asynchronous JavaScript + XML”, and AJAX allows asynchronous server communication. In the case of synchronous processing, you have to send a request from your web browser to the server and wait for the response to come. On the other hand, with asynchronous communication, you don’t need to send a request from the web browser to process the data. For example, when you use Google Maps, there is no transition of images or screens even when you move your position. You can zoom in and move around the map without refreshing the page. Moreover, Google Suggest presents search suggestions the moment you type, so you don’t have to click the search button to see them. This also uses asynchronous communication technology.

By the way, do you know what the XML is? It stands for “Extensible Markup Language”. One of the markup languages used to describe the meaning and structure of documents and data (similar to HTML). However, nowadays, the type JSON is often used for Ajax instead of XML.

Synchronous VS Asynchronous

Synchronous communication

Normally, web pages communicate with the server in what is called synchronous communication. The web browser communicates a request to the server and the response comes back. At this time, the screen turns white for a moment because all the information is being communicated. So that the browser can’t do anything else until it gets the response back from the server.

Asynchronous communication

Some information is requested from the web browser, so the rest of the information remains unchanged. So, the screen will not turn white. So that the browser can do other work even if it doesn’t get a response from the server.

How to create an asynchronous form?


  1. Folder Structure
  2. Create a form with HTML
  3. Write code for AJAX
  4. Import jsonify, render_templae, and request
  5. Receive values in JSON format

1. Folder structure

📁 AJAX_sample
|__📁 templates / index.html

2. Create a form with HTML

First, create a form with HTML. I input the last name and first name and display the result in the output field under the form tag. The ids of the input will be firstname and lastname.

<h1>AJAX Sample</h1>
<form id="form">
<h2>First Name</h2>
<input type="text" id="firstname">
<h2>Last Name</h2>
<input type="text" id="lastname">
<button type="submit" name="button">Submit</button>
<div id="output"></div>

Next, add a jQuery script in head to prepare for AJAX communication. I would use it from Google Developpers.

<script src=""></script>

3. Write code for AJAX

So, how can I get the value from the form? This is the basic way to do it.

  1. Get the submit of the form.
  2. Get destination URL or the form input value.
  3. Submit and show data.
  4. Cancel normal submission.

Let’s write the code for AJAX as follows.

<script type="text/javascript">
$(document).ready(function() {
data : {
firstname : $('#firstname').val(),
lastname : $('#lastname').val(),
type : 'POST',
url : '/'

If you are not familiar with this,


It means that the process in function() will be executed after the HTML is loaded. jQuery (JavaScript) will usually not work properly if you run something without the HTML being fully loaded. So we’ll use this ready.

When the submit button of the form is clicked, AJAX will starts.


AJAX communication starts. It will access HTML. I use the $.ajax() provided in jQuery to communicate with the server via AJAX.


In data:{}, write the id, value, and key name as I set in the input. val() is a method that allows you to get or change the value attribute written in an HTML tag. Type is POST or GET, and URL is the destination URL.

data : {
firstname : $('#firstname').val(),
lastname : $('#lastname').val(),
type : 'POST',
url : '/'

After getting data successfully, add data in output, then show it. show() can be used to show hidden elements.


Lastly, add e.preventDefault.


I have the onSubmit event so that I would use this to undo the process of the original POST.

4. Import jsonify, render_template, and request
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)if __name__ == '__main__'
  • jsonify — Return or create a response in JSON format.
  • render_template — Render HTML for template engine.
  • request — Uses POST and GET.

5. Receive values in JSON format

Receives JSON format values sent via AJAX communication when posted. If there is input data from form, the JSON data will be returned to output.

@app.route('/', methods=['GET','POST'])def index():
if request.method == "POST":
firstname = request.form['firstname']
lastname = request.form['lastname']
output = firstname + lastname
if firstname and lastname:
return jsonify({'output':'Your Name is ' + output + ', right?'})
return jsonify({'error' : 'Error!'})
return render_template('index.html')

def index() returns index.html. (By the way, def is Python function.) In this def, I will set form data, first name, and last name as firstname and lastname. Then create output which is the data combined with firstname and lastname.

If both of form data exists, return output with jsonify. If not, which means I don’t have data, so I would return an error.

Now you can see “Your name is Ayumi Tanaka, right?”, thanks to AJAX!


It is very convenient we can get data without refreshing. Writing the AJAX part is a bit complicated, but mostly pretty simple. You can create this AJAX form with just 60 lines of code!


Source code