7

When I access my page root, my flask generates a base jinja template which contains elements:

<div><span id="var_1">{{ var1|safe }}</span></div>
<div><span id="var_2">{{ var2|safe }}</span></div>
<div><span id="var_3">{{ var3|safe }}</span></div>

In this template I have dropdown menus which using Ajax POSTS their values and then I retrieve them from flask to do some calculations.

function submitValues(val) {
    var entry1 = $('#dropdown1').val(); 
    $.ajax({
    type: "POST",
    url: "/getData",
    data: {entry2_id: val, entry1_id: entry1},
    success: function(data){
    }
    });
}

Once I'm done with the calculations, how can I pass the variables back to ajax to update the 3 elements in the base template with the new 'calculated' variables?

In flask:

@app.route("/getData", methods=['POST'])
def getData():
    entry2Value = request.form['entry2_id']
    entry1Value = request.form['entry1_id']

    #### DO CALCULATIONS HERE WHICH GENERATES 3 NEW VALUES
    #### newVal1, newVal2, newVal3
    #### change var1, var2, var3 from the original template to these new vals
    return ??

I have tried to recall the base template with the new values within the ajax called flask function but this doesn't update the html. The values are obtained from ajax into the function just fine but my issues is how to 're-submit' these values into the base template or even, re-render the template from scratch.

Can I call the 'calculation' flask function by a get() in the ajax 'success' like so:

function submitValues(val) {
    var entry1 = $('#dropdown1').val(); 
    $.ajax({
    type: "POST",
    url: "/getData",
    data: {entry2_id: val, entry1_id: entry1},
    success: function(data){
        $.get("/getData", function(newvar1, newvar2, newvar3)){
        }
    }
    });
}

and then replace the element by id with the new variables?

Thanks!

2 Answers 2

8

The simplest way would be for your Flask route to return a JSON object, so your ajax function can use this returned data.

Below is a working example illustrating this concept:

app.py

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def app_home():
    return render_template("index.html", variable_here = 100)

@app.route("/getData", methods=['GET'])
def getData():

    entry2Value = request.args.get('entry2_id')
    entry1Value = request.args.get('entry1_id')

    var1 = int(entry2Value) + int(entry1Value)
    var2 = 10
    var3 = 15

    return jsonify({ 'var1': var1, 'var2': var2, 'var3': var3 })

app.run(debug=True)

templates/index.html

<html>
<body>

Hello world! <br />

<span id="varID">{{ variable_here }}</span>

<br />

<button id="submit">Submit</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>


$(document).ready(function() {

 $("#submit").click(function() {

    var val = 1;
    var entry1 = 3;

    $.getJSON({
    url: "/getData",
    data: { entry2_id: val, entry1_id: entry1 },
    success: function(data){
        $("#varID").html(data.var1);
    }
    });

 });

});

</script>

</body>
</html>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Matt! I get a TypeError ('dict' object is not callable). Need to jsonify the data? And if I use getJSON instead of ajax I get a 404 error [object%20object] hmm
@dter: Yes, use jsonify(). See the Flask documentation about how to interact with jQuery.
If I have <span id="varID">{{ variable_here }}</span> $("#varID").html(data.var1); would be able to change the content of variable_here to var1 eventhough its a jinja 'element'?
Yes because the jquery is modifying the DOM after the template has already been rendered by jinja
Seems like the output should not be html. When I use $("#var_id").html(data.var1); nothing happens. When I try to put the variable into a normal text ID (i.e. not jinja element) $("#var_id").text(data.js); the variable is shown as text as expected.
|
0

Try this instead return the response in json format from flask to an ajax get request

2 Comments

I tried that but I think the issue here was that the jinja template was already rendered so couldn't change the jinja elements as I wanted. Ended up submitting the form and rerendering the template on submit which requires the page to refresh but works!
Hi @dter could you please explain a little bit more about your final solution which you've mentioned that worked for you. I actually have the same problem, trying to refresh the value of three input objects after some process provoked by a button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.