Estimated reading time: 4 minutes
In our recent blog posting How to Pass a Javascript Variable to Python using JSON, we demonstrated how to easily use AJAX to pass whatever data you wanted and then manipulate it with Python.
In this blog posting, we are going to show how to do this the other way around. The scenario is that you have an application and or website that wants to use data generated through Python, but let Javascript then use it within the application.
As Python can be connected to numerous databases and files ( txt, excel) etc, this piece of logic is very useful for the programmer looking to integrate both programming languages.
Let’s start looking at the code, and see how this can be achieved.
Step 1 – What Files are generated?
This program uses Python Flask to create a web page, that has a drop-down menu. The two files used to generate this are as follows:
(A) app.py – This is the python file that creates a website and loads a template HTML file as outlined below.
(B) Index.html – This is the template file that loads into the browser and runs all the javascript. The javascript loaded here also loads the python data passed over from app.py
Step 2 – APP.PY code overview
The Python library that enables webpage creation is called Flask, and as can be seen below it has to be imported.
In addition, we need to also import render_template which tells the program to go to the templates folder and load “Index.HTML”
The variable that is been passed to JavaScript is called name, and these are the values that you will see in the web browser when it is loaded.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
name = ['Joe','John','Jim','Paul','Niall','Tom']
return render_template('index.html', name=name)
if __name__ == "__main__":
app.run(debug=True)
Step 3 – Index.HTML overview
Here is the template HTML file that runs in the browser. You can add CSS etc to this to make it look nicer and more user friendly.
As you can see it has the usual HTML tags appear as part of a website.
Well look at some of the code further:
In this bit <select id =’select’> </select>, this is the dropdown menu that will appear when Index.html is opened. It will store all the values passed from python. Note that its id is “select”, this will be used later on.
The main parts to focus on next is between <script></script>. This is what reads in the python data and populates it to the dropdown menu.
In step 2 we mentioned that there was a variable called “name”, with values to be passed over.
This is acheived on this line:
var select = document.getElementById(“select”), test = {{ name | tojson }};
Notice that name appears here, and this is referencing back to the exact same value that was discussed in step 2.
For the rest of the lines, I have explained with comments what each does.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pass Python variable to Javascript</title>
</head>
<body>
<select id ='selectvalue'>
</select>
<script>
//name = ['Joe','John','Jim','Paul','Niall','Tom']
var selectvalue = document.getElementById("selectvalue"), test = {{ name | tojson }};
//The increment operator (++) increments (adds one to) its operand and returns a value.
for(var i = 0; i < test.length; i++) // This line checks for the length of the data you feeding in i.e the no of items
{
var selection = document.createElement("OPTION"), // This line creates a variable to store the different values fed in from the JSON object "TEST"
txt = document.createTextNode(test[i]); // This just reads each value from the test JSON variable above
selection.appendChild(txt); // This line appends each value as it is read.
selection.setAttribute("value",test[i]); // This line sets each value read in as a value for the drop down
selectvalue.insertBefore(selection,selectvalue.lastChild); //This reads eah value into the dropdown based on the order in the "TEST" above.
}
</script>
</body>
</html>
Step 4 – What the output looks like!
From step 2, these are values we asked to be used in Javascript to populate a dropdown:
name = [‘Joe’,’John’,’Jim’,’Paul’,’Niall’,’Tom’]