Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render_template in Flask on JS click event [duplicate]

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?

like image 436
Sudeep Avatar asked Nov 30 '25 05:11

Sudeep


1 Answers

$.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";
}
like image 65
bigblind Avatar answered Dec 02 '25 20:12

bigblind