Search code examples
jquerydatatablessql.js

Electron, SQL.JS, jQuery and populating Datatables


I have a table as follows in an app I am creating using Electron. I am using jQuery, Datatables and SQL.js:-

<table id="dataTable" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Date</th>
            <th>Code</th>
            <th>Category</th>
            <th>Hours</th>
            <th>Cost</th>
            <th>Billed</th>
            <th>Description</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Date</th>
            <th>Code</th>
            <th>Category</th>
            <th>Hours</th>
            <th>Cost</th>
            <th>Billed</th>
            <th>Description</th>
        </tr>
    </tfoot>
</table>

The following code to populate the table is not working correctly:-

$(document).ready(function() {

    var DB = null;  

    var t = $('#dataTable').DataTable();

        $(".bottomMenuContainer").on("click", ".loadButton", function(e) {
            var fs = require('fs');
            var sql = require('sql.js');
            var bfr = fs.readFileSync(__dirname + '/../data/EliteData.db');
            DB = new sql.Database(bfr);
            var stmt = DB.prepare("SELECT * FROM ProductEntries ORDER BY Category");
            while(stmt.step()){
                var row = stmt.getAsObject(); 
                t.rows.add([row.Date, row.Code, row.Category, row.Hours, row.Cost, row.Billed, row.Description]).draw(false);
            }
        });



});

I get a requested unknown parameter '1' for row 0, column 1 error message and the data ends up spread over the table when it finally displays, and there are 21 results instead of the 3 in the actual database.

Any idea what's happening?


Solution

  • The answer is to create an array and push the data into the array and then add it to the table. Then draw the table.

                while(stmt.step()){
                    var row = stmt.getAsObject(); 
                    var result = [];
                        result.push(row.Date);
                        result.push(row.Code);
                        result.push(row.Category);
                        result.push(row.Hours);
                        result.push(row.Cost);
                        result.push(row.Billed);
                        result.push(row.Description);
                    t.row.add(result);
                }
                t.draw();