Flask – Calling python function on button OnClick event

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.

Leave a Comment