Reputation: 43
I am working to develop a cascading drop down layout in JavaScript that is populated by arrays created using Python/Flask. I have a Python module and an HTML file and need to pass data and responses between the two.
The first JavaScript drop down menu is already populated with options to choose a name of a type of data. Once a user selects an option this information needs to be passed to the Python module. Then I will use Python ftplib to get information from an FTP server based on the name they selected (a list of years for the chosen set of data). Then, the next drop down will be populated with the list of years. Once a year is chosen, I will again access the FTP server to get a list of days for that year. I have no problem with accessing the information through FTP.
I cannot figure out how to communicate between the Python and the html page. For example, how can I execute a Python function that will return a new array only once the first drop down selection has been made? A second option would be to access the FTP information directly in JavaScript, but I could not find a way to do so nearly as simple as Python ftplib. Any recommendations for how to approach this problem would be helpful.
Upvotes: 1
Views: 3168
Reputation: 11187
well, when flask does the render_template()
it will just fill in the jinja pieces and send the client the HTML page. There really isn't communication with the python on the HTML page.
I would recommend using a POST request and click event
@app.route('/data/')
def get_data(year):
""" get your data here and return it as json """
year = request.form.get('year')
# ...
return jsonify(yourdata)
then, on the js kind of just do
$('.dropdown-button').click(function() {
var year = this.data('year')
$.post('/data/', {'year': year}, function(data) {
// you now have your data as json here
// you can do as you wish with it
})
});
Upvotes: 1
Reputation: 6675
This sounds like a perfect problem for building a Python REST API (possibly using a tutorial like http://tech.pro/tutorial/1213/how-to-build-an-api-with-python-and-flask). You can then call the API using Javascript (one option might be http://api.jquery.com/jquery.ajax/).
Upvotes: 0