I send data from a form with jQuery $.post() to a flask function. The function does some long running calculation the data. In this case, I don't want to send back some HTML but rather render a new template. How can I do this when I call the function with jQuery/AJAX?
The form:
<form id='myform'>
<input type='text'> some input...
<input type='button' value='send form' id='mybutton'>
</form>
Calculation on form input takes some time, so I send it with jQuery:
$.("#mybutton").click(function() {
// get the data in form
$exampledata = 'foo'
$.post("/some/flask/function", {'data': $exampledata}, function(response) {
can I render a new template here with data from flask function?
});
});
In flask, the corresponding function looks like this:
@app.route('/some/flask/function', methods=['POST'])
def longCalculation():
form = request.form
data = form['data']
result = runTheLongCalculation(data)
this does not work -->
return render_template('result.html',r=result)
how can I render a new template after an jQuery/AJAX call?
I don't want to send back a redirect URL and JSON, but actually render a template.
If the template you render is simply a piece of HTML, you can return it like you have shown in your Flask code and do the following in the browser:
$.("#mybutton").click(function() {
// get the data in form
$exampledata = 'foo'
$.post("/some/flask/function", {'data': $exampledata}, function(response) {
var myDiv = $('#resultarea'); // The place where you want to inser the template
myDiv.html(response);
});
});
This expects your Flask template to look something like this:
<div id='result'>
{{ result }}
</div>
It can be bigger, but we are inserting it inside the page so no sidebars, menu navigation or html/body tags, just a simple piece of HTML.
The problem arises if you send back a fully fledged HTML page with your Flask function, as it will not be rendered correctly inside the existing page.
After trying out a lot of ways to do this:
I think the best method to send data from a long running server-side calculation to a new page is to use some kind of server-side storage. This way everything works even if the browser is closed or the user leaves the website.
I go for redis because it's dead simple and fast.
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