Kensuke Kousaka's Blog

Notes for Developing Software, Service.

Note about Flask: How to use jQuery Ajax POST request with Flask

This article describes how to use jQuery Ajax POST request with Flask. Base program that this article uses is created in previously posted article. Please refer to that program.

Edit index.html

Edit index.html by following.

<!DOCTYPE html>
<html lang="ja">
   <meta charset="utf-8"></meta>
   <meta http-equiv="X-UA-Compatible" content="IE=edge"></meta>
   <meta content="width=device-width, initial-scale=1" name="viewport"></meta>
   <!-- Bootstrap CDN -->
   <link rel="stylesheet" href="">
   <link rel="stylesheet" href="">

   <link rel="stylesheet" href="../static/css/sample.css">
   <div class="container-fluid">
     <div class="row">
       <div class="col-sm-12">
         <h1 class="text-center" id="hello">Hello Flask</h1>
         <input type="text" class="form-control" id="input-text" placeholder="Please input text">
         <button class="btn btn-default" id="button">Change text</button>
   <script src=""></script>
   <script src=""></script>
   <script src="../static/js/sample.js"></script>

Add input element that has text attribute to input text.

Edit sample.js

Edit sample.js by following.


function init() {
  $("#button").click(function() {
    var textData = JSON.stringify({"text":$("#input-text").val()});
      success:function(data) {
        var result = JSON.parse(data.ResultSet).result;
    return false;

Get text from previously added input element when button clicked, and send it to Flask using Ajax. Then receive data that is sent from Flask, and modify text without page transition.


Finally, edit by following.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask, render_template
from flask import request, jsonify
import json

app = Flask(__name__)

def index():
   return render_template('index.html')

@app.route('/postText', methods=['POST'])
def lower_conversion():
   text = request.json['text']
   if "ping" in text:
       return_data = {"result":"pong"}
       return jsonify(ResultSet=json.dumps(return_data))
   lower_text = text.lower()
   return_data = {"result":lower_text}
   return jsonify(ResultSet=json.dumps(return_data))

if __name__ == '__main__':"", port=8080)

Specify POST url /postText at sample.js Ajax, add @app.route annotation to method that correspond to, then /postText request sent from sample.js is received at lower_conversion in

Data format of sent data from sample.js is JSON, so get data using request.json when request received at Flask.

In this example, return pong to sample.js if received data contains ping text, otherwise convert all character to lowercase and return this.

Get text and reflect it to Web page when sample.js is received data.

After editting, run and test it.

This sample app is published at k3nsuk3/HelloFlask.