Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: render a page after jQuery ajax $.post call

Tags:

jquery

ajax

flask

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.

like image 858
Martin Preusse Avatar asked Jun 18 '13 14:06

Martin Preusse


2 Answers

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.

like image 163
Christian P. Avatar answered Oct 17 '22 05:10

Christian P.


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.

like image 24
Martin Preusse Avatar answered Oct 17 '22 04:10

Martin Preusse