Error when using data tables, sources order
Hi, I'm making a website with boostrap 5 and I'm trying to make a dataTable type table, only the options that data tables have in boostrap don't work. For a moment it worked fine but I don't really remember what I did that stopped looking good hahha. index.html
I think I have a mistake in the order of my head and where the data table goes.
HTML
<!DOCTYPE html>
<html lang="es">
<head>
<title>Tutorial API JavaScript</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href= "https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="../final/script.js"></script>
</head>
<body>
<h1 class="text-center pt-5 pb-4">Resultados de COVID-19 en Estados Unidos por dia</h1>
<div id="contenedor" class="container">
<table id="data-table" class="table table-striped" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Fecha</th>
<th>Casos positivos</th>
<th>Casos negativos</th>
<th>Muertes</th>
<th>Total de pruebas</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
$(document).ready(function () {
$('#data-table').DataTable();
});
</script>
</body>
</html>
JS
const apiUrl = 'https://api.covidtracking.com/v1/us/daily.json';
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const tableBody = document.querySelector('#data-table tbody');
let count = 0;
data.forEach(item => {
count++;
const row = document.createElement('tr');
const idCell = document.createElement('td');
idCell.textContent = count;
row.appendChild(idCell);
const dateCell = document.createElement('td');
dateCell.textContent = item.dateChecked;
row.appendChild(dateCell); //fecha
const posCell = document.createElement('td');
posCell.textContent = item.positive;
row.appendChild(posCell); //positivo
const negCell = document.createElement('td');
negCell.textContent = item.negative;
row.appendChild(negCell);//negativo
const deadCell = document.createElement('td');
deadCell.textContent = item.death;
row.appendChild(deadCell); //muertes
const resCell = document.createElement('td');
resCell.textContent = item.totalTestResults;
row.appendChild(resCell);//tests
tableBody.appendChild(row);
});
})
.catch(error => {
console.log('Error al obtener los datos:', error);
});
The approach in the question creates each row manually, and adds each data cell to the HTML table - for example:
row.appendChild(idCell);
This does not add any data to your DataTable - it only adds the data to the HTML table (the DOM). That is why you see a message saying "No data available in table" and this is why you cannot sort your data using DataTables. DataTables does not know there is any data.
You can see the data in your web page, because it is in the HTML <table>
.
Instead of building each row of data manually, you can take advantage of DataTables built-in support for Ajax data sources.
This will simplify your code. It will also ensure that the data is added directly to the DataTable - and DataTables will build the HTML contents for you.
Here is a runnable demo:
$(document).ready(function() {
$('#data-table').DataTable({
ajax: {
url: 'https://api.covidtracking.com/v1/us/daily.json',
dataSrc: ''
},
columns: [{
render: function(data, type, row, meta) {
return meta.row + 1;
}
},
{
data: 'dateChecked'
},
{
data: 'positive'
},
{
data: 'negative'
},
{
data: 'death'
},
{
data: 'totalTestResults'
},
]
});
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Covid Data</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
<h1 class="text-center pt-5 pb-4">Resultados de COVID-19 en Estados Unidos por dia</h1>
<div id="contenedor" class="container">
<table id="data-table" class="table table-striped" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Fecha</th>
<th>Casos positivos</th>
<th>Casos negativos</th>
<th>Muertes</th>
<th>Total de pruebas</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
Points to note:
I have used all the latest versions supported by DataTables for Bootstrap 5. See here.
Your JSON data source looks like this:
[
{
"date": 20210307,
"states": 56,
"positive": 28756489,
"negative": 74582825,
...
"positiveIncrease": 41835,
"totalTestResultsIncrease": 1170059,
"hash": "a80d0063822e251249fd9a44730c49cb23defd83"
},
...
{ ... }
]
The JSON array does not have a name - it is just a plain array [ ... ]
. Therefore we need to indicate this to DataTables:
dataSrc: ''
This means "use the unnamed array". If the data had looked something like this:
{
"covid_data": [
{
"date": 20210307,
"states": 56,
"positive": 28756489,
"negative": 74582825,
...
"positiveIncrease": 41835,
"totalTestResultsIncrease": 1170059,
"hash": "a80d0063822e251249fd9a44730c49cb23defd83"
},
...
{ ... }
]
}
Then we would have needed to use this:
dataSrc: 'covid_data'
count++;
for this, as you build your rows. Instead we can use DataTables for this:{
render: function ( data, type, row, meta ) {
return meta.row + 1;
}
}
This defines how that first ID
column is populated. See columns.render for a description of how meta
works.