I've implemented a piece of code that utilizes AJAX calls to refresh an HTML table every 5 seconds.
The approach involves clearing out the content of the table and then appending all data once again every 10 seconds. Here's a snippet of the code:
$('#_appendHere').html('')
$('#_appendHere').append(response);
In this code, _appendHere
represents the table's id
attribute.
Here is the HTML code where the data from my Django view is passed to this page:
<body>
<div>
<div>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
</div>
</div>
<br>
<br>
<br>
<br>
<table id="_appendHere" class="table table-striped table-condensed">
<tr>
<th>Username</th>
<th>Email</th>
<th>Gender</th>
</tr>
{% for item in info_data %}
<tr>
<td>{{item.username}}</td>
<td>{{item.email}}</td>
<td>{{item.gender}}</td>
</tr>
{% endfor %}
</table>
</body>
The CSS styling is as follows:
<style>
table, td, th {
border: 1px solid #ddd;
text-align: left;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 15px;
}
</style>
Additionally, here is the JavaScript part:
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'App1:tempPage' %},
data: {'append_increment': append_increment},
})
.done(function(response) {
$('#_appendHere').html('')
$('#_appendHere').append(response);
append_increment += 10;
});
}, 5000)
A GET request is sent to a URL in a Django view, which renders the same page:
from django.contrib import admin
from django.urls import path,include
from App1 import views
app_name = 'App1'
urlpatterns = [
path('temp/', views.tempPage,name="tempPage"),
]
Finally, the views.py file includes the following logic:
from django.shortcuts import render
from App1.models import Info
def tempPage(request):
info_data = Info.objects.all()
context={"info_data":info_data}
return render(request, 'App1/temp1.html', context)
One issue I've encountered is that the input tag (search box) is also being appended, but only once. Despite attempting to enclose it in a separate div, the problem persists. Any assistance would be greatly appreciated. Thank you!