Need some help with this please "Cannot reinitialise DataTable. "

Need some help with this please "Cannot reinitialise DataTable. "

Hayes7888Hayes7888 Posts: 9Questions: 2Answers: 0

Hi, I am uploading a CSV and displaying the table data - I then need to print the unformatted data.

This works fine doing 1 or the other task but I cant get them to work together as I am using the same DataTable.

I have read about destroying the table but I think it would be better to join the 2 sections together?

Cheers,

<!DOCTYPE html>
<html>
 <head>
  <title>Shopify Payouts</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.6.4/js/dataTables.buttons.min.js"></script>
  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.6.4/js/buttons.print.min.js"></script>


  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


  <script src="https://cdn.datatables.net/plug-ins/1.10.21/api/sum().js"></script>

    
 
  <style>
  

  body {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 12px;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
}

  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Shopify Payouts</h3>
   <br />
   <form id="upload_csv" method="post" enctype="multipart/form-data">
    <div class="col-md-3">
     <br />
    
    </div>  
                <div class="col-md-4">  
                   <input type="file" name="csv_file" id="csv_file" accept=".csv" style="margin-top:15px;" />
                </div>  
                <div class="col-md-5">  
                    <input type="submit" name="upload" id="upload" value="Upload" style="margin-top:10px;" class="btn btn-info" />
                </div>  
                <div style="clear:both"></div>
   </form>
   <br />
   <br />
   <div class="table-responsive">

   


    <table class="col-m-12 table table-striped table-bordered" id="shopify_payouts">
     <thead>
      <tr>
           <th>Date</th>
           <th>Order No.</th>
           <th>Type</th>
           <th>Brand</th>
           <th>Source</th>
           <th>Status</th>
           <th>Payout Date</th>
           <th>Avail. On</th>
           <th>Amount</th>
           <th>Fee</th> 
           <th>Net</th>
      </tr>
      
     </thead>


    </table>


   </div>
  </div>


 

<script>
$(document).ready(function(){



 $('#upload_csv').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"import.php",
   method:"POST",
   data:new FormData(this),
   dataType:'json',
   contentType:false,
   cache:false,
   processData:false,
   success:function(jsonData)
   {
    $('#csv_file').val('');
    $('#shopify_payouts').DataTable({
  

     data  :  jsonData,
     columns :  [
      { data : "Transaction Date" },
      { data : "Order" },
      { data : "Type" },
      { data : "Card Brand" },
      { data : "Card Source" },
      { data : "Payout Status" },
      { data : "Payout Date" },
      { data : "Available On" },
      { data : "Amount" },
      { data : "Fee" },
      { data : "Net" },
     ]




    });
   }



  });

 });
});




// PRINT ME
$(document).ready(function() {
    $('#shopify_payouts').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'print'
        ]
    } );
} );
//


</script>

</body>
</html>

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    As the error says, you're initialising the table twice - on line 106 and again on 141. You can push the Buttons declaration into the first initialisation, and only have it the once,

    Colin

  • Hayes7888Hayes7888 Posts: 9Questions: 2Answers: 0

    Hi Colin, Thats the part I am struggling to do... (am very new to this!)

    I'm not sure where I need the button code.

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951
    Answer ✓

    I would initialize the Datatable once with all the options outside the submit event. Then use rows.add() to add the rows in the ajax success function. Something like this:

    $(document).ready(function(){
     
     
     
     $('#upload_csv').on('submit', function(event){
      event.preventDefault();
      $.ajax({
       url:"import.php",
       method:"POST",
       data:new FormData(this),
       dataType:'json',
       contentType:false,
       cache:false,
       processData:false,
       success:function(jsonData)
       {
        $('#csv_file').val('');
        $('#shopify_payouts').DataTable().rows.add( jsonData ).draw();
       }
     
     
     
      });
     
     });
    });
     
     
     
     
    // PRINT ME
    $(document).ready(function() {
        $('#shopify_payouts').DataTable( {
            dom: 'Bfrtip',
            buttons: [
                'print'
            ],
         columns :  [
          { data : "Transaction Date" },
          { data : "Order" },
          { data : "Type" },
          { data : "Card Brand" },
          { data : "Card Source" },
          { data : "Payout Status" },
          { data : "Payout Date" },
          { data : "Available On" },
          { data : "Amount" },
          { data : "Fee" },
          { data : "Net" },
         ]
     
     
         } );
    } );
    //
    

    Kevin

  • Hayes7888Hayes7888 Posts: 9Questions: 2Answers: 0

    This is great - That has helped a lot! Thank you

  • Hayes7888Hayes7888 Posts: 9Questions: 2Answers: 0

    I'm now trying to add the last 3 columns up and have the 3 totals at the bottom...

    I've been looking at "footerCallback" but am running into the same problem of how to add the extra code...?

    <script>
    $(document).ready(function(){
      
      
      
     $('#upload_csv').on('submit', function(event){
      event.preventDefault();
      $.ajax({
       url:"import.php",
       method:"POST",
       data:new FormData(this),
       dataType:'json',
       contentType:false,
       cache:false,
       processData:false,
       success:function(jsonData)
       {
        $('#csv_file').val('');
        $('#shopify_payouts').DataTable().rows.add( jsonData ).draw();
       }
      
      });
      
     });
    });
      
      
      
      
    // PRINT ME
    $(document).ready(function() {
        $('#shopify_payouts').DataTable( {
            dom: 'Bfrtip',
            buttons: [
                'print'
            ],
    
    // SHOW DATA       
         columns :  [
          { data : "Transaction Date" },
          { data : "Type" },
          { data : "Order" },
          { data : "Card Brand" },
          { data : "Card Source" },
          { data : "Payout Status" },
          { data : "Payout Date" },
          { data : "Available On" },
          { data : "Amount" },
          { data : "Fee" },
          { data : "Net" },
         
          ]
    
    
          // ADD COLUMNS
         
          "footerCallback": function ( row, data, start, end, display ) {
                     var api = this.api(), data;
     
                     // Remove the formatting to get integer data for summation
                     var intVal = function ( i ) {
                         return typeof i === 'string' ?
                             i.replace(/[\$,]/g, '')*1 :
                             typeof i === 'number' ?
                                 i : 0;
                     };
     
                
     
                     // Total over this page
                     pageTotal = api
                         .column( 10, { page: 'current'} )
                         .data()
                         .reduce( function (a, b) {
                             return intVal(a) + intVal(b);
                         }, 0 );
     
                     // Update footer
                     $( api.column( 10 ).footer() ).html(
                         '$'+pageTotal +' ( $'+ total +' total)'
                     );
                 },
     
            } );
        
    
      
      
         } );
    } );
    
    
    
    
    
    
    </script>
    
  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    edited November 2020

    Looks like there's a missing comma on line 52,

    Colin

  • Hayes7888Hayes7888 Posts: 9Questions: 2Answers: 0

    Thanks! I've got it all working perfectly now, the columns add up and it prints as required.... Last issue.... My final "Net" column is showing the total to 13 decimal places?

    <script>
    $(document).ready(function(){
      
      
      
      $('#upload_csv').on('submit', function(event){
       event.preventDefault();
       $.ajax({
        url:"import.php",
        method:"POST",
        data:new FormData(this),
        dataType:'json',
        contentType:false,
        cache:false,
        processData:false,
        success:function(jsonData)
        {
         $('#csv_file').val('');
         $('#shopify_payouts').DataTable().rows.add( jsonData ).draw();
        }
       
       
       
       });
       
      });
     });
       
       
       
       
     
     $(document).ready(function() {
         $('#shopify_payouts').DataTable( {
             
             
             
            // PRINT ME       
             dom: 'Bfrtip',
             buttons: [
                 'print'
             ],
    
    
           // SHOW ME
          columns :  [
           { data : "Transaction Date" },
           { data : "Order" },
           { data : "Type" },
           { data : "Card Brand" },
           { data : "Card Source" },
           { data : "Payout Status" },
           { data : "Payout Date" },
           { data : "Available On" },
           { data : "Amount" },
           { data : "Fee" },
           { data : "Net" },
          
          ],
       
          // ADD ME
                "footerCallback": function ( row, data, start, end, display ) {
                var api = this.api(), data;
     
                // Remove the formatting to get integer data for summation
                var intVal = function ( i ) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '')*1 :
                        typeof i === 'number' ?
                            i : 0;
                };
     
                
     
                // TOTAL "AMOUNT"
                pageTotal = api
                    .column( 8, { page: 'current'} )
                    .data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
     
                // Update footer
                $( api.column( 8 ).footer() ).html(
                    '£'+pageTotal +' '
                );
    
    
    
                // TOTAL FEE
                pageTotal = api
                    .column( 9, { page: 'current'} )
                    .data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
    
                // Update footer
                $( api.column( 9 ).footer() ).html(
                    '£'+pageTotal +' '
                );
    
    
    
    
                // TOTAL NET
                pageTotal = api
                    .column( 10, { page: 'current'} )
                    .data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
     
                // Update footer
                $( api.column( 10 ).footer() ).html(
                    '£'+pageTotal +' '
                );
    
                
            }
        } );
    } );
     
    
    </script>
    
  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    You can use something a Javascript method like toFixed() to format the numbers.

    Kevin

  • Hayes7888Hayes7888 Posts: 9Questions: 2Answers: 0

    I fixed it using

    // Update footer
                $( api.column( 10 ).footer() ).html(
                    
                    '£'+pageTotal.toFixed(2) +' '
    

    Thanks for all the help!

This discussion has been closed.