Issue
I am using flask 2.0 and there is a table on my webpage that shows the status of the transaction. Actually, the status is being updated by calling a MySQL DB hosted in my server. And the table is only updated with the latest data once the webpage is refreshed fully. Is there a way that I can call the MySQL DB and update just the table when I check refresh button next to the table?
The current code and extract is shown below:
Flask App:
cursor.execute('Select * from process WHERE email=%s ORDER BY timestamp DESC LIMIT 20', (email,))
transactions = cursor.fetchall()
return render_template('clientarea.html', transactions=transacions)
HTML:
<table class="table table-hover table-bordered table-sm" style="text-align:center">
<thead>
<tr>
<th scope="col" style="width: 25%">Date</th>
<th scope="col" style="width: 25%">Process Count</th>
<th scope="col" style="width: 25%">Completed Process</th>
<th scope="col" style="width: 25%">Failed Process</th>
</tr>
</thead>
{% for transaction in transactions %}
<tbody>
<tr>
<td>{{ transaction.get('date').strftime("%d %B, %Y") }}</td>
<td>{{ transaction.get('pcount') }}</td>
<td>{{ transaction.get('pcompleted') }}</td>
<td>{{ transaction.get('pfailed') }}</td>
</tr>
</tbody>
{% endfor %}
</table>
Is it possible to load the updated value without refreshing the page using flask?
Solution
use AJAX
Insert this code into head tag in html
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(function () {
$('#refreshBtn').on('click', function () {
$.ajax({
method: 'get',
url: 'http://localhost:5000/table-refresh',
dataType: 'json',
success : function(data){
$.each(data, function(val) {
$('#date_' + data[val][0]).html(data[val][1]);
$('#pcount_' + data[val][0]).html(data[val][2]);
$('#pcompleted_' + data[val][0]).html(data[val][3]);
$('#pfailed_' + data[val][0]).html(data[val][4]);
});
}
});
});
});
</script>
Grant id in table rows, add new refresh button
<td id="date_{{ transaction.id }}">{{ transaction.get('date').strftime("%d %B, %Y") }}</td>
<td id="pcount_{{ transaction.id }}">{{ transaction.get('pcount') }}</td>
<td id="pcompleted_{{ transaction.id }}">{{ transaction.get('pcompleted') }}</td>
<td id="pfailed_{{ transaction.id }}">{{ transaction.get('pfailed') }}</td>
<input type="button" id="refreshBtn" value="refresh" />
Finally, create new router for refreshing table
@app.route('/table-refresh', methods=['GET'])
def table_refresh():
# [[id, date, pcount, pcompleted, pfailed], ...]
arr = [[1, '2021-08-23', 1, 1, 1], [2, '2021-08-24', 1, 1, 1]]
return jsonify(arr)
Answered By - hwanlee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.