vindl
vindl

Reputation: 83

Python Flask Refresh table every 60 seconds

I have posted my flask code below. I want to refresh table data every 60 seconds. Setinterval function is included in html . But however its not refreshing. I am not figuring out exact issue in ajax/Javascript. Please somebody can help to figure out the issue.

App.py:

app = Flask(__name__)
app.config['SECRET_KEY'] = 'dsfd'
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'pwd'
app.config['MYSQL_DATABASE_DB'] = 'db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
eachcur = ["A","B","C","D"]

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

 
    conn = mysql.connect()
    c = conn.cursor()
    data = ((),)
    for curren in eachcur:
      query = "SELECT * from "+curren+" ORDER BY Currid DESC LIMIT 1"
      c.execute(query)
      data = data + c.fetchall()

    conn.close()
    

    return render_template("dashboard.html", data=data)

if __name__ == '__main__':
    app.run(debug=True)

dashboard.html:

<!doctype html>
<html>
 <body>
<script>
 setInterval(function() {
 $.ajax({
  type: "POST",
  url: "/",
 })
  .done(function( data ) {
    $("#table-box").val(data)
   });
  }, 1000 * 60); 
  </script>
<table border="2" cellpadding="4" cellspacing="5" id="table-box" >
{% for row in data %}
    <tr>
    {% for d in row %}
        <td>{{ d }}</td>
    {% endfor %}
    </tr>
{% endfor %}
</table>
 </body>
</html>

Console Output:

jquery.min.js:4 XHR finished loading: POST "http://localhost:5000/".
send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous) @ (index):7
setInterval (async)
(anonymous) @ (index):6
17:21:45.516 jquery.min.js:4 [Violation] 'load' handler took 334ms

Console snapshot

Console snapshot - 2

Upvotes: 2

Views: 7280

Answers (1)

Jim Wright
Jim Wright

Reputation: 6058

There are a couple of things wrong with your code:

  1. You are using .val() where you should be using .html()

    .val() is used to set the value of things like input fields, not overwrite entire DOM objects. You should be using .html() here instead.

  2. You are assigning non-html data to #table-box

    Your for statement generating the table is only going to run on page load. You need to regenerate all of the table rows in the AJAX .done() handler.

See my example below that fixes both of these issues.

<!doctype html>
<html>
 <body>
<script>
 setInterval(function() {
 $.ajax({
  type: "POST",
  url: "/",
 })
  .done(function( data ) {
    console.log(data);
    var tableHtml = '';
    for (row in data) {
      tableHtml += '<tr>';
      for (d in row) {
        tableHtml += '<td>' + d + '</td>';
      }
      tableHtml += '</tr>';
    }
    $("#table-box").html(tableHtml)
   }).fail(function(jqXHR, textStatus, errorThrown) {
     console.log(jqXHR, textStatus, errorThrown);
   });
  }, 1000 * 60); 
  </script>
<table border="2" cellpadding="4" cellspacing="5" id="table-box" >
{% for row in data %}
    <tr>
    {% for d in row %}
        <td>{{ d }}</td>
    {% endfor %}
    </tr>
{% endfor %}
</table>
 </body>
</html>

EDIT: It doesn't look like you have a route/controller set up the handle the AJAX request to POST /. You should try something like this:

@app.route('/json', methods= ['GET'])     
def display_deals_json():
  conn = mysql.connect()
  c = conn.cursor()
  data = ((),)
  for curren in eachcur:
    query = "SELECT * from "+curren+" ORDER BY Currid DESC LIMIT 1"
    c.execute(query)
    data = data + c.fetchall()
  conn.close()
  return json.dumps(data)

You will need to update your AJAX command to:

$.ajax({
  type: "GET",
  url: "/json",
})

Upvotes: 2

Related Questions