I have a site that makes an AJAX post to a Flask route.
I know there are many similar questions (please don't mark as duplicate) that use the AJAX success method to handle the response. That would work in my simplified example, but the route in my actual code is pulling a bunch of data from a database that gets rendered to multiple tables. I'd prefer not to rewrite all the table data updates in JavaScript, so I really just need to re-render the template.
python:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def hello_world(message=None):
return render_template('test.html', message=message)
app.run()
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 () {
$.post(window.location.href, {'test': 'test'});
});
});
</script>
</head>
<body>
{{ message }}
<button id="mybutton" name="mybutton" type="button">Click Me!</button>
</body>
</html>
I've looked for the answer to this question on many pages and none of them worked until I found the one that releases the AJAX call so that the rerender is allowed to take place:
$('form').on('submit', function(event) {
$.ajax({
type: 'POST',
url: "{{ url_for( 'myServerFunction' ) }}",
data: JSON.stringify({'myId':bunchOfIds}),
contentType: "application/json",
success:function(response){ document.write(response); }
})
The most important line is the success line that releases the document so that it can be rerendered.
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