Enrico Rossi

Python bottle and ajax

This is just a little tips to demonstrate how to use the python bottle micro framework to render a page template which send a js async request (ajax), get the result in a json form and display it.

First create this bottle main file, for example main.py, this will respond onto localhost:8080 as described in the bottle manual.

The first route ’localhost:8080/’ will render the template json.tpl file which will see later, the second route ’localhost:8080/getallitems' will send to the browser the json converted dictionary.

#!/usr/bin/env python

from bottle import route, run, template, get, debug


# this will be the dictionary returned by the ajax call.
# Bottle convert this in a json compatibile string.

items = {1: 'first item', 2: 'second item'}

# a simple json test main page
def jsontest():
    return template('json')

def shop_aj_getallitems():
    return (items)

run(host='localhost', port=8080)

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

The json.tpl template file looks like this:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<script type="text/javascript">
var xmlhttp;

// Are we using a modern browser or ...
if (window.XMLHttpRequest) {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
} else {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

// This will render the two output which substitute the
// elements id="raw" and id="forin"
function GetItems()
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    // var jsonobj = eval ("(" + xmlhttp.responseText + ")"); 
    var jsonobj = JSON.parse(xmlhttp.responseText); 

    var output = xmlhttp.responseText;
    document.getElementById("raw").innerHTML = output;

    output = "";

    for (i in jsonobj) {
      output += '<p>';
      output += i + " : " + jsonobj[i];
      output += '</p>';

    document.getElementById("forin").innerHTML = output;

  } else {
    alert("data not available");

// xmlhttp.onreadystatechange = GetArticles;
// the GetItems function will be triggered once the ajax
// request is terminated.
xmlhttp.onload = GetItems;

// send the request in an async way
xmlhttp.open("GET", "/getallitems.json", true);

  <p>The raw result from the ajax json request is:</p>
  <div id="raw"></div>
  <br />
  <p>The for cycle produces :</p>
  <div id="forin"></div>

Run the program with:

python main.py

open the URL on http://localhost:8080

The raw result from the ajax json request is:
{"1": "first item", "2": "second item"}

The for cycle produces :
1 : first item
2 : second item