Search on blog:

Python: How to use AJAX in Flask using jQuery.

After all there was two problems:

  • HTML wasn't serve from flask/server. And browser could block it for security reason. I put HTML directly in function index() but later you can use render_template("filename.html")

  • you forgot to load javascript jQuery library.

Other: Flask - Calling python function on button OnClick event

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin


app = Flask(__name__)
CORS(app, support_credentials=True)


@app.route('/')
def index():
    return """
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type=text/javascript>
   $(function() {
     $('a#sender').bind('click', function() {
       $.getJSON('/background_process_test',
         function(data) {
           console.log(data);
           window.alert(data['success'])  
         });
       return false; // stop <a> to send normal request
     });
   });
</script>

<form>
    <a href=# id="sender"><button>Send AJAX</button></a>
</form>

</div>"""

@app.route('/background_process_test')
@cross_origin(supports_credentials=True)
def background_process_test():
    print("Hello AJAX")
    return jsonify({'success': 'OK'})


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000)

Notatki:

Stackoverflow Problem with Ajax and flask, what is the problem?

If you like it
Buy a Coffee