0

I am trying to create rows that refresh every minute, I have created the table in html and am adding rows to it via javascript. is there a way i can get these rows to refresh every minute without appending more rows to the bottom of the table

Table in my .html file below

<table class="table table-dark" id = "statsTable">
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Symbol</th>
      <th scope="col">Price </th>
      <th scope="col">Day High</th>
      <th scope="col">Day Low</th>
      <th scope="col">Market Cap</th>
      <th scope="col">%24h</th>
    </tr>
  </thead>
  <tbody id = "stats">
  </tbody>
</table>

javascript below


{% block jquery %}
var endpoint = '/api/table/data'
populateTable()

function populateTable(){
$.ajax({
  method: "GET",
  url: endpoint,
  success: function(data){
    console.log(data)
    var table_data ='';

    for (var key in data){
      table_data += '<tr>';
      table_data += '<td><a href = "{% url 'webapp-graph'%}"><img src="https://www.cryptocompare.com'+data[key].EUR.IMAGEURL+'"alt="'+key+'logo" style =" width:3em; height:auto;"></a></td>';
      table_data += '<td>' +key+ '</td>'
      table_data += '<td>' +data[key].EUR.PRICE+ '</td>';
      table_data += '<td>' +data[key].EUR.HIGHDAY+ '</td>';
      table_data += '<td>' +data[key].EUR.LOWDAY+ '</td>';
      table_data += '<td>' +data[key].EUR.MKTCAP+ '</td>';

      if (data[key].EUR.CHANGEPCT24HOUR[0] == '-') {
        table_data += '<td style = "color:red">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>';
      } else {
        table_data += '<td style = "color:green">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>';
      }
      table_data += '</tr>';
    }
    $('#stats').append(table_data);
    },
  })
}
 {% endblock %}

Philip
  • 67
  • 7

2 Answers2

0

You can use setTimeout to poll the server at specified intervals. At the end of your popualateTable function you can add setTimeout(populateTable,1000); See this post for more info.

Taylor
  • 1,223
  • 1
  • 15
  • 30
  • Thanks Taylor. I have tried this method but instead of overwriting the existing rows the rows are being added to the bottom of the table – Philip Apr 22 '19 at 21:02
  • I am not a jquery wizard but I would try this. `$("#stats tr").remove();`. I would add it above `var table_data = ' '` – Taylor Apr 22 '19 at 21:25
0

You could have a django view that returns the rendered table:

def some_view(request):
    data_table = get_data_table()
    return render_to_string("table.html", data_table)

and call that form you js via ajax, the result will be your html table which you can then insert/replace the html in some div.

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60