Mr.Cisco
Mr.Cisco

Reputation: 31

How to auto refresh html table fields rendered with a for loop in flask?

Snippet from the function in Flask. I'm generating a list of all positions and then sending them over. Then using jinja and the for loop I'm populating the table.

@app.route("/")
def table_list():
   position_list=["a","b","c","d"]
   return render_template("index.html",
              position=position_list)

This is on the homepage and needs to be automatically refreshed every couple of seconds so the position values will get updated.

The HTML table:

 <table>
   <tbody id="data">
        {% for pos1, pos2, pos3, pos4 in position %}
           <tr id="data_table">
               <td id="pos1"> {{ pos1 }} </td>
               <td id="pos2"> {{ pos2 }} </td>
               <td id="pos3"> {{ pos3 }} </td>
               <td id="pos4"> {{ pos4 }} </td>
       {% endfor %}
    </tbody>
</table>

How do I use JS to refresh only the values in the table, and automatically every couple of seconds?

Upvotes: 1

Views: 1542

Answers (1)

Yok Chirathivat
Yok Chirathivat

Reputation: 116

You will have to change multiple things to make this work.

  1. Separate endpoint into html endpoint and web-service endpoint.
    @app.route("/table_list")
    def table_list():
        return render_template("index.html")
    
    @app.route("/get_list")
    def get_list():
        position_list = ["a", "b", "c", "d"]
        return make_response({"output": position_list})
  1. Change the html for table
    <table>
        <tbody id="data">
        <tr id="data_table">
        </tr>
        </tbody>
    </table>
  1. Change the html template to keep calling get_list and refresh the html
    </body>
    
    <script>
        setInterval(function () {
            let myRequest = new Request('/get_list');
            fetch(myRequest).then(response => response.json()).then(function (data) {
                let data_table = document.getElementById("data_table");
                data_table.innerHTML = "";
                for (let d in data['output']) {
                    data_table.innerHTML += `<td>${data['output'][d]}</td>`
                }
            });
        }, 1000);
    </script>

</html>

Upvotes: 2

Related Questions