0

Flask is not re-rendering the template page with the new variable.

Flask code (app.py):

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)


@app.route("/",methods = ['GET', 'POST'])
@app.route("/<value>",methods = ['GET', 'POST'])
def index(value=1):
    print(value)
    return render_template('home.html',number=value)

@app.route("/next",methods = ['GET', 'POST'])
def next():
    if request.method == 'POST':
        last_num = list(dict(request.form).keys())[0]
        last_num = int(last_num)
        return redirect(url_for("index",value=last_num+1))

if __name__ == '__main__':
    app.run()

HTML page (home.html):

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
    $('#submit').click(function() {
        $.ajax({
            url: '/next',
            data: String(Number(document.getElementById("number").textContent)),
            type: 'POST',
            success: function(response) {
                console.log("Awesome");
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});
</script>
</head>
<body>

<div id="number">
  {{number}}
</div>
<button type="button" id="submit">Next</button>

</body>
</html>

The (last) number in HTML page nicely reaches the flask code and the index function gets the incremented value also. But the HTML page do not reload with the new number variable.

Pushpendu Ghosh
  • 105
  • 1
  • 2
  • 7
  • (1) Why have you disabled `onClick` in HTML but applied the same in JS ? (2) Redirect to a page from Ajax call is not straightforward (since the browser doesn't expect it). Have a look at this answer: https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call – Rahul Bharadwaj Mar 29 '20 at 08:11
  • @RahulBharadwaj Is there any cleaner way to communicate from HTML to Flask (instead of ajax) and using the data to rerender the HTML page from Flask? – Pushpendu Ghosh Mar 29 '20 at 08:34

1 Answers1

1

Couple things.

Firstly, you can interpolate your flask variables directly into your JavaScript. It may cause errors in your editor (not in this case), but when the page renders, it will work properly. (ie. data: "{{ number|safe }}")

Secondly, you are not redirecting the client. You are returning a redirect from your API call, but you are not following it. That function only works if you were rendering the /next endpoint as your page. You should instead return the URL you want the client to navigate to. You can set the page URL a number of ways in JavaScript. If you just want to reload the page, put location.reload(true) in your success handler. (by putting forceGet to true, you will prevent the browser for reloading from the cache so the server will actually update the variable on the page). Note that if you do this, you will need to store the variable globally on your backend as it will not update otherwise. That might be your problem now (if you are manually reloading the page each time): your variable is only being passed via the redirect which again, you are not following and rendering.

Finally, I would say there are better ways to accomplish what you are trying to do. Maybe store the variable locally and update it in a database remotely. No need to reload the page for something this trivial.

Hope this helps. Please let me know if I have misunderstood your problem or I have made a mistake.

ComedicChimera
  • 466
  • 1
  • 4
  • 15