Flask - Calling python function on button OnClick event
Solution 1:
You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.
In app.py put below code segment.
#rendering the HTML page which has the button
@app.route('/json')
def json():
return render_template('json.html')
#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
print ("Hello")
return ("nothing")
And your json.html page should look like below.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').on('click', function(e) {
e.preventDefault()
$.getJSON('/background_process_test',
function(data) {
//do nothing
});
return false;
});
});
</script>
//button
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.
Solution 2:
It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.
I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.
With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);
Then in your html, use this:
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...To execute your moving forward code. And include this:
{{ forward_message }}
... where you want the moving forward message to appear on your template.
This will cause your page to reload, which is inevitable without using AJAX and Javascript.
Solution 3:
Easiest solution
<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>