I have a data table that I am trying to append rows to when there is new data to display. I'm relatively inexperienced so I took the easy way out on this and wanted to write a script that checked the database for updates every second instead of listening for server-sent events. I tried to write an Ajax query that would get all the objects in the data table, and if their 6th value is false (which means they have not been loaded), then it would add a row to my data table with that information. My tables are in a Django webapp, and here's the code I have tried to implement:
<script type="text/javascript">
$(document).ready(function(){
var table = $('#example').DataTable();
setInterval(function(){
newrequests = $.ajax({
type: "GET",
url: "/main/newrequests/",
// I tried this and it didn't work
// success: function(data) {
// for(i = 0; i < data.length; i++){
// // check if the request has been loaded
// if(data[i][5] == 0)
// // if not, load and set to loaded
// table.row.add(data[i]).draw;
// data[i][5] == 1;
// }
// }
});
for(i=0; i<newrequests.length; i++){
if (newrequests[i][5] == 0){
table.row.add(newrequests[i]).draw();
newrequests[i][5] = 1;
}
}
}, 1000)
});
</script>
I have a view set up for /main/newrequests which simply all the objects in the database:
def newrequests(request):
return HttpResponse(Request.objects.all())
When I update the database, the data table does not refresh. Does anyone know what I am doing wrong? I feel like it might be how I am trying to use Ajax.