-1

I have a flask app and want to update a value in a template periodically. This value will come from a Flask route. For example my views are defined like so:

from . import main
from flask import render_template


@main.route('/')
def index():
    return render_template('index.html')


@main.route('/price')
def price():
    return 5

Now my index.html:

<html>
<body>

<p id="p1">Replace this text</p>

<script>
  setInterval(function(){
    document.getElementById("p1").innerHTML = "some value";
  }, 5000);
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

How can I call the /price route from within the js and then use the returned value in id=p1?

0

1 Answer 1

3

I think, it is better to return a structured response (json/xml) from views.

So, my first suggestion is about your 'price' view:

views

@app.route('/price')
def price():
    # obtain jsonify from Flask: from flask import jsonify
    # you may change the output/format as you need
    return jsonify({'value': 5})

Using jquery (which simplifies AJAX calls),

index.html

<html>
<body>

<p id="p1">Replace this text</p>

<script>
  setInterval(function(){
    $.get('/price',function(data) {
        // here, we have the data object returned by 'price' endpoint
        // you can access its attributes as a regular JSON object
        document.getElementById("p1").innerHTML = data.value;
    });
  }, 5000);
</script>

<p>The paragraph above was changed by a script.</p>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.