Kensuke Kousaka's Blog

Notes for Developing Software, Service.

Note for communicating JSON data between jQuery and Python CGI using Ajax

This article notes how to communicate JSON formatted data between jQuery Ajax and Python CGI.

index.html

<!DOCTYPE html>
<html lang=ja>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AjaxPythonCGI</title>
    <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">
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-12 col-md-12">
          <h1 class="text-center">Click below button to send sample text</h1>
          <button type="button" class="btn btn-default btn-lg pull-right" id="button">Send</button>
        </div>
      </div>
      <div class="row">
        <div class="col-sm-12 col-md-12">
          <textarea class="form-control" rows="2" placeholder="Received text is show here" id="result" disabled></textarea>
        </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="js/sample.js"></script>
  </body>
</html>

sample.cgi

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

import sys
import json

print("Content-type: application/json")
print("\n\n")

data = sys.stdin.read()
params = json.loads(data)
text = params['text']


result = {'text': text}

print(json.JSONEncoder().encode(result))
print('\n')

sample.js

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

function init() {
  console.log("init");
  $("#button").click(function() {
    console.log("clicked");
    var text = "Sample text";
    send(text);
  });
}

function send(text) {
  console.log(text);
  var json = JSON.stringify({'text': text});
  
  $.ajax({
    type: 'POST',
    url: 'cgi/sample.cgi',
    contentType: 'application/json',
    data: json,
    success: function(data) {
      console.log(data);
      console.log(data.text);
      $('#result').empty();
      $('#result').val(data.text);
    }
  });
  
  return false;
}

Add Sample text value into text variable, and send to sample.cgi with JSON formatted text variable through send() method when index.html Send button is clicked.

sample.cgi, which written in Python 3, read received data using sys.stdin.read() and load as JSON using json.loads(). After that, read data by specifying JSON key to text which defined at sample.js.

To return data to sample.js from Python CGI using Ajax, convert data into dictionary, format JSON using json.JSONEncoder().encode(), and print() it.

Returned data from sample.cgi is set to data argument which defined at success: function() in sample.js. Returned data's key was defined as text in sample.cgi so that read data by data.text here.