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">
 <head>
   <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>
   <title>HelloFlask</title>
   <!-- Bootstrap CDN -->
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

   <link rel="stylesheet" href="../static/css/sample.css">
 </head>
 <body>
   <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>
       </div>
     </div>
   </div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   <script src="../static/js/sample.js"></script>
 </body>
</html>

Add input element that has text attribute to input text.

Edit sample.js

Edit sample.js by following.

$(window).load(init());

function init() {
  $("#button").click(function() {
    var textData = JSON.stringify({"text":$("#input-text").val()});
    $.ajax({
      type:'POST',
      url:'/postText',
      data:textData,
      contentType:'application/json',
      success:function(data) {
        var result = JSON.parse(data.ResultSet).result;
        $("#hello").text(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.

Edit app.py

Finally, edit app.py 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__)


@app.route('/')
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__':
   app.run(host="127.0.0.1", port=8080)

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

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 app.py and test it.

This sample app is published at k3nsuk3/HelloFlask.