Checkbox: display page after jQuery ajax $ .post call

I am sending form data with jQuery $ .post () to the bulb function. The function performs some lengthy data calculations. In this case, I do not want to send the HTML code, but instead render a new template. How to do this when I call a function using jQuery / AJAX?

The form:

<form id='myform'> <input type='text'> some input... <input type='button' value='send form' id='mybutton'> </form> 

Computing the input of the form takes some time, so I submit it using 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 the bulb, 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 the redirect URL and JSON, but actually create a template.

+6
source share
2 answers

If the template you created is just an HTML snippet, you can return it as shown in your flask code and do the following in a 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 may be larger, but we insert it inside the page so that there are no sidebars, menu navigation or html / body tags, just a simple piece of HTML.

The problem arises if you submit a fully-fledged HTML page using the Flask function, as it will not display correctly on an existing page.

+4
source

Having tried many ways to do this:

I think the best way to send data from a long server-side session to a new page is to use some kind of server storage. Thus, everything works even if the browser is closed or the user leaves the website.

I go to redis because he is dead simple and fast.

+1
source

Source: https://habr.com/ru/post/947559/


All Articles