Push variable with HTML-Table to Datatables

Push variable with HTML-Table to Datatables

pekabopekabo Posts: 7Questions: 2Answers: 1

Hi @ all,

I read a csv file and generate a table in a variable (see script). How do I push the "html" variable to datatable to get this result DataTables.

$.get('stock.csv', function(data) {

    // start the table  
    var html = '<table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">';

    // split into lines
    var rows = data.split("\n");

    // parse lines
    j = 0;
    rows.forEach( function getvalues(ourrow) {  
        if(j == 0)
        {
            // start a table row
            html += "<thead><tr>";

            // split line into columns
            var columns = ourrow.split(",");
            
            var arrayLength = columns.length;
            for (var i = 0; i < arrayLength; i++) {             
                html += "<th>" + columns[i] + "</th>";              
            }       
            // close row
            html += "</tr></thead>";
            j++;
        }
        else
        {
            // start a table row
            html += "<tr>";

            // split line into columns
            var columns = ourrow.split(",");
            
            var arrayLength = columns.length;
            for (var i = 0; i < arrayLength; i++) {
                if (i == 0) {
                    html += "<th>" + columns[i] + "</th>";
                }
                else{
                    html += "<td>" + columns[i] + "</td>";
                }
            }       
            // close row
            html += "</tr>";
        }
    })
    // close table
    html += "</table>";

    // insert into div
    $('#container').append(html);       
});

This question has an accepted answers - jump to answer

Answers

  • F12MagicF12Magic Posts: 109Questions: 0Answers: 28

    Seems like your code doesn't generate a TBODY tag. Probably that's causing problems.
    Further, you need to include the JavaScript and css files referenced below the example you're referencing and initialize the datatable.

  • pekabopekabo Posts: 7Questions: 2Answers: 1
    edited December 2016

    Hi F12Magic,

    I changed the code, with the same effect. I thinks my Problem is the timing. See picture the CSV "stock.csv" loads to late.

    I thought, i could first render everythink to a Variable and then push this to Variable to dataTables.

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>DataTables example - Bootstrap styling</title>
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
    
    
        <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    
        <script type="text/javascript">
            $(window).bind("load", function() {
                // Code here start
    
                $.get('stock.csv', function(data) {
    
                    // start the table 
                    var html = '<table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">';
    
                    // split into lines
                    var rows = data.split("\n");
    
                    // parse lines
                    j = 0;
                    rows.forEach(function getvalues(ourrow) {
                            if (j == 0) {
                                // start a table row
                                html += "<thead><tr>";
    
                                // split line into columns
                                var columns = ourrow.split(",");
    
                                var arrayLength = columns.length;
                                for (var i = 0; i < arrayLength; i++) {
                                    html += "<th>" + columns[i] + "</th>";
                                }
                                // close row
                                html += "</tr></thead><tbody>";
                                j++;
                            } else {
                                // start a table row
                                html += "<tr>";
    
                                // split line into columns
                                var columns = ourrow.split(",");
    
                                var arrayLength = columns.length;
                                for (var i = 0; i < arrayLength; i++) {
                                    if (i == 0) {
                                        html += "<th>" + columns[i] + "</th>";
                                    } else {
                                        html += "<td>" + columns[i] + "</td>";
                                    }
                                }
                                // close row
                                html += "</tr><tbody>";
                            }
                        })
                        // close table
                    html += "</table>";
    
                    // insert into div
                    $('#container').append(html);
                });
    
                // Code here end
            });
        </script>
    
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
    </head>
    
    <body>
        <!-- where the content will go -->
        <div id="container"></div>
    
    </body>
    
    <script type="text/javascript">
        output(function() {
                    $(document).ready(function() {
                            $('#example').DataTable({
                                html
                            });
                        }
                    });
    </script>
    
    </html>
    
  • F12MagicF12Magic Posts: 109Questions: 0Answers: 28
    edited December 2016

    Try loading all css and scripts files in the head tag.
    Then just before closing the body tag you insert your own javascript to generate the table. After you append the table to the div, you initialize the datatable.
    Example:

    <!DOCTYPE html>
    <head>
    <meta tags>
    <title></title>
    Load css files
    Load js files
    </head>
    <body>
    <div id="container"></div>
    <script>
    $(document).ready(function() {
        $.get('stock.csv', function(data) {
            ....
            your code tot generate the table
            ....
            $('#container').append(html);
            $('#example').DataTable();
        }
    });
    </script>
    </body>
    </html>
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin

    After you append the table to the div, you initialize the datatable.

    I think this is the key bit.

    Allan

  • pekabopekabo Posts: 7Questions: 2Answers: 1

    Thank you F12Magic,

    appreciate your help! I post your Solution for my problem, may it help some order user.

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>DataTables example - Bootstrap styling</title>
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
    
        <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>   
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
    </head>
    <body>
        <!-- where the content will go -->
        <div id="container"></div>
        
        <script type="text/javascript">
            $(document).ready(function() {
    
                $.get('stock.csv', function(data) {
                    // start the table 
                var html = '<table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">';
             
                // split into lines
                var rows = data.split("\n");
             
                // parse lines
                j = 0;
                rows.forEach( function getvalues(ourrow) { 
                    if(j == 0)
                    {
                        // start a table row
                        html += "<thead><tr>";
                        htmltfoot = "<tfoot><tr>";
             
                        // split line into columns
                        var columns = ourrow.split(",");
                         
                        var arrayLength = columns.length;
                        for (var i = 0; i < arrayLength; i++) {            
                            html += "<th>" + columns[i] + "</th>";
                            htmltfoot += "<th class='sum'></th>";       
                        }      
                        // close row
                        html += "</tr></thead>";
                        htmltfoot += "</tr></tfoot></tbody>";
                        html += htmltfoot;
                        j++;
                    }
                    else
                    {
                        // start a table row
                        html += "<tr>";
             
                        // split line into columns
                        var columns = ourrow.split(",");
                         
                        var arrayLength = columns.length;
                        for (var i = 0; i < arrayLength; i++) {
                            if (i == 0) {
                                html += "<th>" + columns[i] + "</th>";
                            }
                            else{
                                html += "<td>" + columns[i] + "</td>";
                            }
                        }      
                        // close row
                        html += "</tr>";
                    }
                })
                // close table
                html += "</tbody></table>";
             
                // insert into div
                    $('#container').append(html);
                    $('#example').DataTable();
                });
                // Code here end
            });
        </script>
    </body>
    </html>
    

    above the "how do I Load a CSV in Datatables." solved question

    From here I have a continuing question. As you can see I add a the tfooter. How I can get the Sum of each Column in the footer. Till now no luck with the sum plugin or footercallback

    I wish all readers merry Christmas 2016

  • pekabopekabo Posts: 7Questions: 2Answers: 1

    I cant find the right place where to intergrate follwing code in my code (see above) to get sum of all columns.

    "footerCallback": function(row, data, start, end, display) {
        var api = this.api();
    
        api.columns('.sum', { page: 'current' }).every(function () {
            var sum = api
                .cells( null, this.index(), { page: 'current'} )
                .render('display')
                .reduce(function (a, b) {
                    var x = parseFloat(a) || 0;
                    var y = parseFloat(b) || 0;
                    return x + y;
                }, 0);
            console.log(this.index() +' '+ sum); //alert(sum);
            $(this.footer()).html(sum);
        });
    }
    
  • F12MagicF12Magic Posts: 109Questions: 0Answers: 28
    Answer ✓

    Just place the footerCallback code inside the dataTables initialisation. Like:

    $('#example').DataTable(
        {
            "footerCallback": function(row, data, start, end, display) {
                ...
            }
        }
    );
    

    Or take a look at the footer callback example on this site.
    Or an example on codepen made by me.

This discussion has been closed.