johnab
johnab

Reputation: 15

How to do auto-reloading of jinja 2 data in Flask without refreshing page?

I'm trying to load the data into json2 template as soon as there is new data available without refreshing the page but I'm unable to do that, this is what I tried till now main Function

@app.route("/")
def index1():
return render_template("index.html",gamest=get_games())

endpoint on the server that returns info.

@app.route("/sys_info.json")
def index():
     return get_games()

jinja 2 scripts:

<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="content">{{ index }}</div> {# this is the original system_info passed in from the root view #}

<script>
setInterval(function(){ // load the data from your endpoint into the div
    $("#content").load("/sys_info.json")
},1000)
</script>

<div class="list-group">
            {% for  game in gamest %}
            <a class="score-size text-xs-center nounderline list-group-item list-group-item-action" >
               <div class="row">
                  <div class="col-xs-4">
                     {% if game["Batting_team_img"] %}
                     <img class="team-logo" src="/static/{{ game["Batting_team_img"] }}">
                     {% endif %}
                     {{ game["Batting team"] }}  {{ game["runs10"] }}
                     </b>
                     <br>
                     {{ game["wickets10"] }}
                  </div>

I can see only change in the value in terminal but I can't see any changes in webpage data remains static, how can I fix this so data are changed dynamically in the website without refreshing page?

Upvotes: 1

Views: 1914

Answers (1)

mberacochea
mberacochea

Reputation: 1796

The data is requested but the html is not refreshed by the js script. You have to add the logic for the browser to load the data in the html. For example:

setInterval(function() {
    // load the data from your endpoint into the div
    $.getJSON("/sys_info.json", function (data) {
       $.each(data, function (_, element) {
         $('.list-group').append('<div>' + elment['Batting team'] + '</div>);
       });
    })
},1000)

You need the client browser to do the same you do on the server with jijna.

Upvotes: 1

Related Questions