I have a page with a button that makes a ajax
post
to a flask
route. I'd like the route to compute a message (simplified by hardcoding for the example) and passes it back to another route and reloads the page the user is on. redirect(urlfor())
does call the other route, but render_template
seems not to be called as the page doesn't reload.
init.py
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/second_route', methods=['POST'])
def second_route():
print request.json
return redirect(url_for('hello_world', message='test'))
@app.route('/')
def hello_world(message=None):
return render_template('index.html', message=message)
app.run()
index.html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#mybutton').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/second_route",
data: JSON.stringify({}),
success: [],
dataType: "json"
});
});
});
</script>
</head>
<body>
{{ message }}
<button id="mybutton" name="mybutton" type="button">Click Me!</button>
</body>
</html>