Home > database >  Python flask script not executing as expected
Python flask script not executing as expected

Time:02-11

I'm trying to execute a function based on a button click via javascript. I've copied a tutorial on how to do this, but nothing happens.

I've added a break point in the function that should be executed (background_process_test), but the program never executes the function. What am I missing to get this simple tutorial working? I'm running on a local machine with waitress.

python code:

from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve

app = Flask(__name__)

#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")


if __name__ == "__main__":
    app.debug = True
    
serve(app, host='0.0.0.0', port=8080) #WAITRESS!

html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <!--<script src="/jquery/jquery-3.6.0.min.js"></script>-->
    <script src="{{url_for('static', filename='jquery-3.6.0.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>
</head>


<body>
    <div class='container'>
        <h3>Test</h3>
            <form>
                <a href=# id=test><button class='btn btn-default'>Test</button></a>
            </form>

    </div>
</body>
</html>

enter image description here

Update: Network tab

CodePudding user response:

i somehow deleted the '$' sign. It was giving an error due to spacing in visual studio. Setting the spacing right, solved the issue. Many thanks for pointing me in the right direction.

CodePudding user response:

There is a typo in the following code:

('a#test').on('click', function(e) {
  ...
})

Specifically, your attempt to use jquery get the list of elements that match 'a#test'. The code should be:

$('a#test').on('click', function(e) {
  ...
})
  • Related