I am trying to call a function in Flask by clicking a button. When the button is clicked, the following script runs.
JS
$("#load_btn").click(function() {
$.get("/callback");
}
Flask
@app.route('/callback')
def callback():
print('called')
... # code here that needs to run before rendering callback
return render_template('callback.html')
The problem here is, called is printed, and GET /callback HTTP/1.1 200 is logged as well, but callback.html is not rendered - the page stays the same. I'm guessing this is probably not the best approach to solving this problem, but if so what is the recommended approach?
$.get just sends an HTTP request to your server, but doesn't actually do anything anything with the data (in your case, the rendered template) it gets back from the server.
Try something like this:
$("#load_btn").click(function() {
$("html").load("/callback");
}
Or if the template you render doesn't contain any <head> tags, only body content, you can do
$("#load_btn").click(function() {
$("body").load("/callback");
}
Or, you can exchange "body" for a specific element to only replace a specific part of the page.
If you want the user to be redirected, do this:
$("#load_btn").click(function() {
window.location = "/callback";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With