I have a javascript function that extracts data from a database, puts it into an html table, and puts that table into an HTML page via a document.getElementById command. Everything works fine except when I load the HTML page, the data is not in the table. I am using the innerHTML property to put the table on the page. My question is, is this a valid way of populating a table to an HTML page? I have posted the relevant code below.
<div class="content mt-3">
<div class="animated fadeIn">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<strong class="card-title">Data Table</strong>
</div>
<div class="card-body">
<table id="results-data-table" class="table table-striped table-bordered">
<!-- I am trying to put the html here from javascript
</table>
</div>
</div>
</div>
</div>
</div><!-- .animated -->
</div><!-- .content -->
<script src="../controllers/query.js">getData()</script>
<script src="assets/js/vendor/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="assets/js/plugins.js"></script>
<script src="assets/js/main.js"></script>
Javascript:
function getData() {
var sql = require("mssql");
var dbConfig={
server:"server",
database: "db",
user:"user",
password: "pw"
}
var conn = new sql.Connection(dbConfig);
var req = new sql.Request(conn);
conn.connect(function (err){
if (err) {
console.log(err);
return;
}
req.query("SELECT * FROM table",resultsCallback)
conn.close();
});
}
function resultsCallback (err, recordset) {
var tableify = require('tableify');
if (err) {
console.log(err);
}
else {
var html = tableify(recordset);
html = html.replace('<table>','');
html = html.replace('</table>','');
document.getElementById("results-data-table").innerHTML=html;
}
};