Multiple tables on same page.

Multiple tables on same page.

bbrindzabbrindza Posts: 316Questions: 73Answers: 1

I am looking for some suggestions.

I have Bootstrap homepage that allows a user to open multiple tabs from a navigation link. (see image and code below).

It is designed to give the user the ability to open the same table in a different tab.

The link contain in the navigation link, fires the same script, but I received the dreaded. DataTables warning: table id=FCLookupTable - Cannot reinitialise DataTable.

So I found this code $('table.display').DataTable() which I used for the initialization.

The error was eliminated, but I did not get data from my ssp ajax call.

I am not sure what I am missing. Any advice would be greatly appreciated.

    <table id='' class="table table-striped table-bordered" style="width:100%">
        <thead>
          <tr>
             <th></th>
             <th>Claim</th>
             <th>Location</th>
             <th>Department</th>  
             <th>Vendor<br>Customer</th>
             <th>Pro<br>Number</th>
             <th>Freight<br>Carrier</th>
             <th>Claim<br>Amount</th>
             <th>Freight<br>Claimed</th>
             <th>Total<br>Claim</th>
             <th>Amount<br>Paid</th>
             <th>Amount<br>Due</th>
             <th>Status</th>
             <th>Ship<br>Date</th>
             <th>Received<br>Date</th>
             <th>Claim<br>Type</th>
             <th>Created<br>Aging</th> 
             <th>Filed<br>Aging</th>
           </tr> 
            <tr id="filterrow">
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th>
             <th></th> 
             <th></th>
           </tr> 
      </thead>
     <tbody>
    </table>
$(document).ready(function() {

     var viewType = '<?php echo $_GET['viewType'] ?>';

     if(viewType == 'live'){ 
            var ssp = "FreightClaims/ssp_FreightClaimManagement.php";
     }else{
            var ssp = "FreightClaims/ssp_FreightClaimArchive.php";
            document.getElementById('createFreightClaim').style.display = 'none';   
     };

     // Setup - add a text input to each header cell
     $('#FCLookupTable thead tr#filterrow th:gt(0)').each( function () {
       $(this).html( '<input type="text" size="1" onclick="stopPropagation(event);" placeholder="Search" />' );
     });

    // Apply the filter
     $("#FCLookupTable thead input").on( 'keyup change', function () {
         table
             .column( $(this).parent().index()+':visible' )
             .search( this.value )
             .draw();
     } );

    var table = $( 'table.display').DataTable( {
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]], 
        order: [[ 1, "desc" ]],
           pageLength: 15,
        dom: 'RlBfrtip',
        buttons: [
                   'excelHtml5',
               ],
        pagingType: "full_numbers",
        language: {search: "Table Search: "},
        processing: true,
        serverSide: true,
        ajax: ssp,
                language: {
                    processing:  
                      '<i class="fa fa-sync fa-spin fa-2x fa-fw"></i><span>  Loading Data...</span>' 
                 } ,
        columns: [
                  { className:'detail-level-control',
                    orderable: false,
                    data: null,
                    defaultContent: '',
                    width: '1px'
                   },
                  { data: "claim_number_link"},
                  { data: "location" },
                  { data: "department_name" },
                  { data: "vendor_customer" },
                  { data: "pro_number" },  
                  { data: "carrier_name"},
                  { data: "claim_amount" },
                  { data: "freight_claim_amount" },   
                  { data: "total_claim_amount"},
                  { data: "amount_paid" },
                  { data: "amount_due" },
                  { data: "status" },
                  { data: "ship_date"  },
                  { data: "received_date" },
                  { data: "claim_type" },
                  { data: "created_age" },
                  { data: "filed_age" }
                 ],
         select: {
                   style:    'os',
                   selector: 'td:first-child'
                  },
         colReorder: true,
         orderCellsTop: true,
    });//END .dataTable    

    table.columns().iterator( 'column', function (ctx, idx) {
            $( table.column(idx).header() ).append('<span class="sort-icon"/>');
    } );

    //******************************************************
    //Event listener for opening and closing detail level 1
     $('#FCLookupTable tbody').on('click', 'td.detail-level-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row( tr );

        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row and call getChildDetail function
            row.child( getChildDetail (row.data()) );
            row.child( formatChildDetail() ).show();
            tr.addClass('shown');
        }
    } );
     $('div.dataTables_filter input').focus();    
} );//END $(document).ready(function() 

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    The error was eliminated, but I did not get data from my ssp ajax call.

    Have you looked at the Network Inspector to make sure the ajax call is issued twice and to see what is returned?

    Do you get errors in the browser's console?

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Hi Kevin,

    Oddly enough I am not even getting a ajax call to the ssp_FreightClaimManagement.php. when the application initially loads the default tab.

    My Chrome Network tab does not show that it fired.

    I put an alert(ssp); right before the table initialization and it shows the value of ssp_FreightClaimManagement.php , which is the variable used in ajax: ssp.

    It works fine when I use a hardcode ID (ie. #FCLookupTable ) but not when I use
    $( 'table.display').DataTable.

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    Didn't notice at first but you have $( 'table.display').DataTable({...}); but yout t=table has this:

    <table id='' class="table table-striped table-bordered" style="width:100%">
    

    You don't have the class display. You can probably just use $( 'table').DataTable({...}); assuming you don't have other table tags that aren't going to be Datatables. Or you can add a class name that distinguishes the Datatables tables from the non-Datatables tables.

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    That display worked and the ajax loaded, but the DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable came back, even though both tables loaded correctly. .

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    When does the error occur?

    Is something else being called that might initialize Datatables?

    Can you post a link or create a test case so we can see your code flow?

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Kevin ,
    Unfortunately my environment is behind a corporate fire wall using a DB2 database tables for the ssp, so I am unable to offer a test case.

    However I can provide you the 2 scripts that make up this application (see following for homePage.php and next post that contains FreightClaimManagementBS.php script).

    Home Page

    <!DOCTYPE html>
    <html lang='en'>
    
    <head>
      <meta charset='utf-8'>
      <meta http-equiv='X-UA-Compatible' content='IE=edge'>
      <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
      <title>Traffic</title>
    
      <link rel='stylesheet' type='text/css' href='/fontawesome/css/all.min.css'> 
      <link rel='stylesheet' type='text/css' href='/jquery-ui/jquery-ui.min.css'>
      <link rel='stylesheet' type='text/css' href='/DataTables/dataTables.bootstrap4.min.css'>
      <link rel='stylesheet' type='text/css' href='/DataTables/Buttons/css/buttons.dataTables.css'> 
      <link rel='stylesheet' type='text/css' href='/DataTables/RowGroup/css/rowGroup.dataTables.min.css'>
      <link rel='stylesheet' type='text/css' href='/DataTables/Select/css/select.dataTables.min.css'>
      <link rel='stylesheet' type='text/css' href='/HomePageTemplate/homePage.css'>
      <link rel='stylesheet' type='text/css' href='/DataTables/FixedHeader/css/fixedHeader.dataTables.min.css'>
     
    <style>
    th{ 
        text-align:left; 
        font-size:0.75em;
        padding-bottom: 6px;
        padding-top: 6px; 
        word-wrap:break-word;
    } 
    td{ 
         font-family:Sans-serif; 
         font-size:0.75em;
        text-align:left; 
    } 
     thead input { width: 100% } 
    
    .dataTables_length{ padding-bottom:10px}
    
    td.detail-level-control {   
       background: url('../../images/details_open.png') no-repeat center center;    
       cursor: pointer;    
    }    
    tr.shown td.detail-level-control {  
       background: url('../../images/details_close.png') no-repeat center center;   
    }  
    dataTables_wrapper .dataTables_processing {
        position: absolute;
        top: 15% !important;
    }
    .sidebar .nav-item .nav-link span { font-size: 0.95em;}
    .dropdown-menu{font-size: 0.90em;}
    .contentTabDiv {
      margin-top: 10px;
      margin-left: 3px;
    }
    .nav-tabs .nav-item {
      margin-bottom: -2px;
      border-bottom: 1px solid #ffffff;
    }
    .nav-tabs > li .close {
      margin: 2px 0 0 10px;
      font-size: 15px;
    }
    button,
    button:active,
    button:focus {
      outline: none;
      font-family: Sans-serif;
      font-size: 0.95em;
    }
    </style>
    </head>
    
    <body id='page-top'>
    
    <nav class='navbar navbar-expand navbar-dark bg-dark static-top'>
    
     <a class='navbar-brand mr-1' href='#'>Traffic</a>
    
     <button class='btn btn-link btn-sm text-white order-1 order-sm-0' id='sidebarToggle' href='#'>
          <i class='fas fa-bars'></i>
     </button>
    
     <!-- Navbar Search -->
     <form class='d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0'>  
     
     </form>  
    
    <!-- Top Navigation Bar -->
      <ul class='navbar-nav ml-auto ml-md-0'>
    
      <div class='topbar-divider d-none d-sm-block' ></div>
            <div class='dropdown-menu dropdown-menu-right' aria-labelledby='userDropdown'>
             <a class='dropdown-item' href='#' data-toggle='modal' data-target='#logoutModal'>Close Home Page</a>
            </div>
          </li>
        </ul>
      </nav>
    
    <!-- Side Navigation Bar -->  
      <div id='wrapper'>
        
      <ul  id='navItem' class='sidebar navbar-nav'>
    
     <!--  Freight Claim Management ->
     <li class='nav-item active'>
        <a class='nav-link' id='freightClaimManagement' onclick="loadTabContent('FreightClaims/FreightClaimManagementBS.php?viewType=live', 'Freight Claim Management')">
         <i class='fas fa-fw fa-table'></i>
         <span id='nameSpan'>Freight Claim Management</span>
        </a>
     </li>
    
     <!-- Freight Claim Archive -->
     <li class='nav-item'>
         <a class='nav-link' id='freightClaimArchive' onclick="loadTabContent('FreightClaims/FreightClaimManagement.php?viewType=archive', 'Freight Claim Archive', '', '')">
         <i class='fas fa-fw fa-table'></i>
         <span id='nameSpan'>Freight Claim Archive</span>
        </a>
     </li>
    </ul> 
    
    <!-- Content Header -->
     <div id='content-wrapper'>
       <div>
           <ul id='tabs' class='nav nav-tabs'>  
               <li id='tab_0'class='nav-item'>  
               <a href='#tabContent_0' class='nav-link active' data-toggle='tab'>Freight Claim Management</a>
             </li>  
    
          </ul>  
       <div  id='tabContent' class='tab-content'>
       <div id='tabContent_0' class='container-fluid tab-pane fade show active'>
            <!-- Main Content Area where application scripts can be loaded using jQuery load in the loadScript() function -->
      </div>
    
       </div>  
    
      </div>
    </div> <!-- /.content-wrapper -->
    </div>
    
     <!-- Scroll to Top Button-->
      <a class='scroll-to-top rounded' href='#page-top'>
        <i class='fas fa-angle-up'></i>
      </a>
    
    <!-- Logout Modal  -->
     <div class='modal fade' id='logoutModal' tabindex='-1' role='dialog' aria-labelledby='logoutModalLabel' aria-hidden='true'>
        <div class='modal-dialog' role='document'>
          <div class='modal-content'>
            <div class='modal-header'>
              <h5 class='modal-title' id='logoutModalLabel'>Ready to Leave?</h5>
              <button class='close' type='button' data-dismiss='modal' aria-label='Close'>
                <span aria-hidden='true'>×</span>
              </button>
            </div>
            <div class='modal-body'>Select 'Close Home Page' below if you are ready to end your current session.</div>
            <div class='modal-footer'>
              <button class='btn btn-secondary' type='button' data-dismiss='modal'>Cancel</button>
              <a class='btn btn-primary' onclick='logout()'>Close Home Page</a>
            </div>
          </div>
        </div>
      </div>
    
      <!-- jQuery Library - Core Home Page Template-->
     <script type='text/javascript' src='/jquery/jquery.min.js'></script>
     <script type='text/javascript' src='/DataTables/datatables.min.js'></script> 
     <script type='text/javascript' src='/bootstrap/dist/js/bootstrap.bundle.min.js'></script>
     <script type='text/javascript' src='/DataTables/dataTables.bootstrap4.min.js'></script>
     <script type='text/javascript' src='/jquery-ui/jquery-ui.min.js'></script>
     <script type='text/javascript' src='/DataTables/Buttons/js/dataTables.buttons.min.js'></script> 
     <script type='text/javascript' src='/DataTables/Buttons/js/assets/buttons.html5.js'></script>
     <script type='text/javascript' src='/DataTables/Buttons/js/assets/buttons.flash.js'></script>
     <script type='text/javascript' src='/DataTables/RowGroup/js/dataTables.rowGroup.min.js'></script>
     <script type='text/javascript' src='/DataTables/Select/js/dataTables.select.min.js'></script>
     <script type='text/javascript' src='/HomePageTemplate/homePage.js'></script>
     <script type='text/javascript' src='/Chosen/chosen.jquery.min.js'></script>
     <script type='text/javascript' src='/DataTables/FixedHeader/js/dataTables.fixedHeader.min.js'></script>
    
     <script>
     var tabNumber = 0;  //** Global variable used as the ID of the close tab button. 
     var nextTabNumber = 0;  //** Global variable to track number of tabs open. 
     var tabID = '';
     var tabContentID = '';
    
    // *Load Default Content for Home Page
    
     $('#tabContent_0').load('FreightClaims/FreightClaimManagementBS.php?viewType=live'); 
     
    //* Add active class to the nav_item 
      
     var navItem = document.getElementById('navItem');
     var item = navItem.getElementsByClassName('nav-item');
     var nameSpan = document.getElementById('nameSpan');
     
      for (var i = 0; i < item.length; i++) {
         
       item[i].addEventListener('click', function() {
           
       var current = document.getElementsByClassName('active');
       current[0].className = current[0].className.replace(' active', '');
       
       this.className += ' active';
    
       });
     }
    //* loadTabContent 
    function loadTabContent(url, tabLabel){
    
        nextTabNumber++;
        tabNumber++;
    
        tabID = 'tab_'+ nextTabNumber;
        tabContentID = 'tabContent_'+ nextTabNumber;
        tabContentHREF = '#tabContent_'+ nextTabNumber;
    
        $("<li id='"+ tabID +"' class='nav-item'></li>" ).appendTo( "#tabs" );
        $("<a href='"+ tabContentHREF +"' class='nav-link' data-toggle='tab'><button  id='"+ tabNumber +"' class='close' type='button' onclick='closeTab(this.id)'>x</button> "+ tabLabel +" </a>").appendTo("#"+ tabID +"" );
    
        $("<div id='"+ tabContentID +"' class='container-fluid tab-pane fade'>" ).appendTo( "#tabContent" );
        
        $("#"+ tabContentID +"" ).load(url); 
    }
    //* closeTab 
    function closeTab(tabNumber){
    
      var currentTabID = 'tab_' + tabNumber;
      var element = document.getElementById(currentTabID);
    
      if(element !== null){
          element.parentNode.removeChild(element);
      }
    
      $('.nav-tabs a[href="#tabContent_0"]').tab('show');
    }
    </script>
    </body>
    </html>
    
  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    **DataTables HTML (part of FreightClaimManagementBS.php **

    <form name="FC_Loookup" method="post">
    <table id="" class="table display table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
           <th></th>
           <th>Claim</th>
            <th>Location</th>
             <th>Department</th>  
             <th>Vendor<br>Customer</th>
             <th>Pro<br>Number</th>
             <th>Freight<br>Carrier</th>
             <th>Claim<br>Amount</th>
             <th>Freight<br>Claimed</th>
             <th>Total<br>Claim</th>
             <th>Amount<br>Paid</th>
             <th>Amount<br>Due</th>
             <th>Status</th>
             <th>Ship<br>Date</th>
             <th>Received<br>Date</th>
              <th>Claim<br>Type</th>
              <th>Created<br>Aging</th> 
              <th>Filed<br>Aging</th>
            </tr> 
             <tr id="filterrow">
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th>
               <th></th> 
               <th></th>
              </tr> 
          </thead>
         <tbody>
         </tbody>
      </table>
     </form>
    
  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    **JS for FreightClaimManagementBS.php **

    <script type="text/javascript">
    var trHTML = '';            //** Global variable to store TR payable or order data in getChildDetail function.
    var thHTML = '';            //** Global variable to store TH payable or order data in getChildDetail function.
    var childHeaderLabel = '';  //** Global variable to store payable or order label in getChildDetail function.
    //*************************************************************************
    //Start - document.ready  
    //**************************************************************************
    $(document).ready(function() {
    
         var viewType = '<?php echo $_GET['viewType'] ?>';
         
         if(viewType == 'live'){ 
                var ssp = "FreightClaims/ssp_FreightClaimManagement.php";
         }else{
                var ssp = "FreightClaims/ssp_FreightClaimArchive.php";
                document.getElementById('createFreightClaim').style.display = 'none';   
         };
         
         // Setup - add a text input to each header cell
         $('table.display thead tr#filterrow th:gt(0)').each( function () {
           $(this).html( '<input type="text" size="1" onclick="stopPropagation(event);" placeholder="Search" />' );
         });
         
        // Apply the filter
         $("table.display thead input").on( 'keyup change', function () {
             table
                 .column( $(this).parent().index()+':visible' )
                 .search( this.value )
                 .draw();
         } );
    
        var table = $('table.display' ).DataTable( {
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]], 
            order: [[ 1, "desc" ]],
            pageLength: 15,
            dom: 'RlBfrtip',
            buttons: [
                       'excelHtml5',
                   ],
            pagingType: "full_numbers",
            language: {search: "Table Search: "},
            processing: true,
            serverSide: true,
            ajax: ssp,
            language: {
                        processing:  
                          '<i class="fa fa-sync fa-spin fa-2x fa-fw"></i><span>  Loading Data...</span>' 
                     } ,
            columns: [
                      { className:'detail-level-control',
                        orderable: false,
                        data: null,
                        defaultContent: '',
                        width: '1px'
                       },
                      { data: "claim_number_link"},
                      { data: "location" },
                      { data: "department_name" },
                      { data: "vendor_customer" },
                      { data: "pro_number" },  
                      { data: "carrier_name"},
                      { data: "claim_amount" },
                      { data: "freight_claim_amount" },   
                      { data: "total_claim_amount"},
                      { data: "amount_paid" },
                      { data: "amount_due" },
                      { data: "status" },
                      { data: "ship_date"  },
                      { data: "received_date" },
                      { data: "claim_type" },
                      { data: "created_age" },
                      { data: "filed_age" }
                     ],
             select: {
                       style:    'os',
                       selector: 'td:first-child'
                      },
             colReorder: true,
             orderCellsTop: true,
        });//END .dataTable    
    
        table.columns().iterator( 'column', function (ctx, idx) {
                $( table.column(idx).header() ).append('<span class="sort-icon"/>');
        } );
    
        //******************************************************
        //Event listener for opening and closing detail level 1
         $('table.display tbody').on('click', 'td.detail-level-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row( tr );
     
            if ( row.child.isShown() ) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // Open this row and call getChildDetail function
                row.child( getChildDetail (row.data()) );
                row.child( formatChildDetail() ).show();
                tr.addClass('shown');
            }
        } );
         $('div.dataTables_filter input').focus();    
    } );//END $(document).ready(function() 
    
    
  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    I'm not seeing the second script. You are getting this error:

    table id=DataTables_Table_0 - Cannot reinitialise DataTable

    Somewhere in your code flow you are initializing the Datatable again. Does this happen on page load or are you doing something that causes the error?

    You will need to follow your code to see how/when the datatable is being reinitialized. It could be you need to use $.fn.dataTable.isDataTable() to keep from reinitializing the Datatatble. ITs hard to say where to put it without access to see how your code is working.

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Child row functions in FreightClaimManagementBS.php

    //******************************************************//
    //* Start - getChildDetail                             *//
    //******************************************************// 
    function getChildDetail (d){
    
        childHeaderLabel = '';
        thHTML ='';
        trHTML = '';
    
        var claimNumber = d.claim_number;
    
        if (parseFloat(d.total_claim_amount)  < 30.00){
            var under30 = 'Y'
        }else{
            under30 =''
        }
        
        if (d.claim_type == 'Inbound'){
    
        //** Start - getPayableData.
        $.ajax
            ({
                type: "POST",
                url:  "FreightClaims/getPayable.php", 
                data: {claimNumber: claimNumber},      
                dataType: 'json',
                cache: false,
                async: false,
                success: function (data) {
    
                        var diff = 0;
                         
                        $.each(data, function (i, payableData) {
                          
                            var poNumber = '<td>' + payableData.PONumber + '</td>';
                           
                            var paidFlag = '<span class="red-text">' + payableData.paidFlag + '</span>';
                            
                            var payableNumber = '<td>' + payableData.payableNumber  + ' ' + paidFlag +'</td>';
                            
                            var payableTotal = '<td>' + parseFloat(payableData.payablesTotalAPAmount).toFixed(2);+ '</td>';
            
                            var invoiceNumber = '<td>' + payableData.invoiceNumber + '</td>';
                                        
                            var invoiceTotal = '<td>' + payableData.invoiceAmount + '</td>';
            
                            diff = payableData.invoiceAmount - payableData.payablesTotalAPAmount  
    
                            if(diff == 0){
                                               var difference = '<td>' + diff.toFixed(2) + '</td>';
                                         }else{
                                               var difference = '<td class="red-text">' + diff.toFixed(2) + '</td>';
                                         }
             
                            var creditPayable = '<td>' + payableData.creditPayable + ' </td>';
    
                            var creditAmount = '<td>' + payableData.creditAmount + ' </td>';
                                 
                            trHTML += '<class="detail_level tr>'+ poNumber + payableNumber +  payableTotal + invoiceNumber + invoiceTotal  + difference + creditPayable + creditAmount +'</tr>';
    
                         });//*End -  $.each(data, function (i, payableData)
    
                    childHeaderLabel = '<p id="childHeaderLabel" style="padding-left:50px">Payable Information</p>' ;
                    thHTML += '<thead ><tr><th class="detail_level">P.O. #</th><th class="detail_level">Payable #</th><th class="detail_level">Payable Total</th><th class="detail_level">Invoice #</th><th class="detail_level">Invoice Total</th><th class="detail_level">Difference</th><th class="detail_level">Credit Payable</th><th class="detail_level">Credit</th></tr>' 
                     
                }//* End -getPayableData.php success: function (data)
            }); //* End - getPayableData.php AJAX
    
        }else{
    
            //Start - getCreditDebit AJAX
            $.ajax
                ({
                    type: "POST",
                    url:  "FreightClaims/getCredit.php", 
                    data: {claimNumber: claimNumber,
                           under30: under30},      
                    dataType: 'json',
                    cache: false,
                    async: false,
                    success: function (data) {
                               
                     $.each(data, function (i, creditDebitData) {
                            var orderNumber = '<td>' + creditDebitData.FCCREDITProOrderPONumber + '</td>';
                       
                            var creditPayable = '<td>' + creditDebitData.creditPayable + ' </td>';
                        
                            var payableTotal = '<td>' + creditDebitData.payableAmount + '</td>';
    
                            var creditDebitNumber = '<td>' + creditDebitData.FCCREDITCreditDebit + '</td>';
    
                            trHTML += '<class="detail_level tr>'+ orderNumber + creditPayable +  payableTotal + creditDebitNumber + '</tr>';
                                                    
                      });//*End -  $.each(data, function (i, payableData)
    
                     childHeaderLabel = '<p id="childHeaderLabel" style="padding-left:50px">Order Information</p>' ;
                     thHTML += '<thead class="ul"><th class="detail_level">Order Number</th><th class="detail_level">Credit Payable</th><th class="detail_level">Credit Payable Total</th><th class="detail_level">Credit Debit Number</th></thead>'    
    
                   }//* End -getPayableData.php success: function (data)
                }); //* End - getPayableData.php AJAX
            }//* END - if (d.claim_type == 'Inbound')
        
    }//* END - getChildDetail  *//
    //*****************************************************//
    //Start - formatChildDetail                           *//
    //*****************************************************//
    function formatChildDetail() {
    
         return '<table id="detail_level" cellpadding="0" cellspacing="0" border="0" style="padding-left:50px;">'+
    
         childHeaderLabel + 
    
         thHTML +
            
         trHTML +
    
         '</table>';
    }
    //*************************************** 
    function stopPropagation(evt) {
        if (evt.stopPropagation !== undefined) {
            evt.stopPropagation();
        } else {
            evt.cancelBubble = true;
        }
    } 
    </script>
    
  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    as Kevin said, it would help to see this. We don't need the complete environment, just strip it down to the minimum code needed to reproduce the error,

    Colin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    The Home Page script loads the initial first Tab content by loading the script FreightClaims/FreightClaimManagementBS.php (line 184 in Home Page)

    // *Load Default Content for Home Page

    $('#tabContent_0').load('FreightClaims/FreightClaimManagementBS.php?viewType=live');

    When the link "Freight Claims Management" is clicked, the second tab is loaded with the table, but that is when I receive the error message.

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Colin,
    What I posted is about as stripped down I can get it , without losing the main functionality .

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    I will try to strip out more code.

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    When the link "Freight Claims Management" is clicked, the second tab is loaded with the table, but that is when I receive the error message.

    What event is executed when you change tabs? This event must be reinitializing Datatables. As I mentioned above use $.fn.dataTable.isDataTable() to determine if the Datatable has been initialized or not.

    You've posted. lot of code to try debugging manually which is difficult. If you are unable ot provide a test case link that we can run then you will need to follow your code to determine why the reinitialization error is occurring. Start by placing breakpoints everywhere you initialize Datatables. This will allow you to see where this is happening.

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Following are the 2 scripts with the minimal code to produce error .

    HomePageTest.php using FreightClaimManagementTest.php to load content.

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1
    <!DOCTYPE html>
    <html lang='en'>
    
    <head>
      <meta charset='utf-8'>
      <meta http-equiv='X-UA-Compatible' content='IE=edge'>
      <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
    
      <title>Traffic</title>
    
      <link rel='stylesheet' type='text/css' href='/jquery-ui/jquery-ui.min.css'>
      <link rel='stylesheet' type='text/css' href='/DataTables/dataTables.bootstrap4.min.css'>
      <link rel='stylesheet' type='text/css' href='/Chosen/chosen.min.css'>
      <link rel='stylesheet' type='text/css' href='/DataTables/Buttons/css/buttons.dataTables.css'> 
      <link rel='stylesheet' type='text/css' href='/DataTables/RowGroup/css/rowGroup.dataTables.min.css'>
      <link rel='stylesheet' type='text/css' href='/DataTables/Select/css/select.dataTables.min.css'>
      <link rel='stylesheet' type='text/css' href='/HomePageTemplate/homePage.css'>
     
    <style>
     th{ 
        text-align:left; 
        font-size:0.75em;
        padding-bottom: 6px;
        padding-top: 6px; 
        word-wrap:break-word;
      } 
        
      td{ 
        font-family:Sans-serif; 
        font-size:0.75em;
        text-align:left; 
    /*     padding:1px; */
     } 
     thead input { width: 100% } 
    
       
    .dataTables_wrapper .dataTables_processing {
        position: absolute;
        top: 15% !important;
    }
      .contentTabDiv {
            margin-top: 10px;
            margin-left: 3px;
        }
     .nav-tabs .nav-item {
            margin-bottom: -2px;
            border-bottom: 1px solid #ffffff;
        }
        
     .nav-tabs > li .close {
            margin: 2px 0 0 10px;
            font-size: 15px;
      }
    
    </style>
    </head>
    
    <body id='page-top'>
    
     <div id='content-wrapper'>
      <button type='button'  onclick="loadTabContent('FreightClaims/FreightClaimManagementTest.php?viewType=live', 'Freight Claim Management')">Load 2nd Tab</button> 
     
       <div>
           <ul id='tabs' class='nav nav-tabs'>  
           
             <li id='tab_0'class='nav-item'>  
                  <a href='#tabContent_0' class='nav-link active' data-toggle='tab'>Freight Claim Management</a>
             </li>  
    
          </ul>  
          
       <div  id='tabContent' class='tab-content'>
         <div id='tabContent_0' class='container-fluid tab-pane fade show active'>
            <!-- Main Content Area where application scripts can be loaded using jQuery load in the loadScript() function -->
         </div>
       </div>  
    
      </div>
      
    </div> <!-- /.content-wrapper -->
    
    <script type='text/javascript' src='/jquery/jquery.min.js'></script>
    <script type='text/javascript' src='/DataTables/datatables.min.js'></script> 
    <script type='text/javascript' src='/bootstrap/dist/js/bootstrap.bundle.min.js'></script>
    <script type='text/javascript' src='/DataTables/dataTables.bootstrap4.min.js'></script>
    <script type='text/javascript' src='/jquery-ui/jquery-ui.min.js'></script>
     
     <script>
    
    // Get meta data from about modal
     var webPageName = "<?php echo basename($_SERVER['PHP_SELF']) ?>" // Returns The Current PHP File Name 
     var dirPath = "<?php echo dirname($_SERVER['PHP_SELF']) ?>" // Returns The directory path )
     var url = dirPath +'/'+ webPageName; 
     
     $('#aboutModalDescriptionSpan').text($('meta[name=description]').attr("content")); 
     $('#aboutModalAuthorSpan').text($('meta[name=author]').attr("content"));   
     $('#aboutModalURLSpan').text(url);
     
     var tabNumber = 0;  //** Global variable used as the ID of the close tab button. 
     var nextTabNumber = 0;  //** Global variable to track number of tabs open. 
     var tabID = '';
     var tabContentID = '';
    //*************************************************************************
    // Load Default Content for Home Page
    //************************************************************************* 
     $('#tabContent_0').load('FreightClaims/FreightClaimManagementTest.php?viewType=live'); 
     
    //*************************************************************************
    // Add active class to the nav_item 
    //************************************************************************* 
     var navItem = document.getElementById('navItem');
     var item = navItem.getElementsByClassName('nav-item');
     var nameSpan = document.getElementById('nameSpan');
     
      for (var i = 0; i < item.length; i++) {
         
       item[i].addEventListener('click', function() {
           
       var current = document.getElementsByClassName('active');
       current[0].className = current[0].className.replace(' active', '');
       
       this.className += ' active';
    
       });
     }
    //*************************************************************************
    // loadTabContent 
    //************************************************************************* 
    function loadTabContent(url, tabLabel){
    
        nextTabNumber++;
        tabNumber++;
    
        tabID = 'tab_'+ nextTabNumber;
        tabContentID = 'tabContent_'+ nextTabNumber;
        tabContentHREF = '#tabContent_'+ nextTabNumber;
    
        $("<li id='"+ tabID +"' class='nav-item'></li>" ).appendTo( "#tabs" );
        $("<a href='"+ tabContentHREF +"' class='nav-link' data-toggle='tab'><button  id='"+ tabNumber +"' class='close' type='button' onclick='closeTab(this.id)'>x</button> "+ tabLabel +" </a>").appendTo("#"+ tabID +"" );
    
        $("<div id='"+ tabContentID +"' class='container-fluid tab-pane fade'>" ).appendTo( "#tabContent" );
        
        $("#"+ tabContentID +"" ).load(url); 
    }
    //*************************************************************************
    // closeTab 
    //************************************************************************* 
    function closeTab(tabNumber){
    
      var currentTabID = 'tab_' + tabNumber;
      
      var element = document.getElementById(currentTabID);
    
      if(element !== null){
          element.parentNode.removeChild(element);
        }
    
      $('.nav-tabs a[href="#tabContent_0"]').tab('show');
    }
    //***************************************************************************
    </script>
    
    </body>
    </html>
    
  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1
    <form>
        <table id="" class="table display table-striped table-bordered" style="width:100%">
            <thead>
              <tr>
                 <th>Claim</th>
                 <th>Location</th>
                 <th>Department</th>  
                 <th>Vendor<br>Customer</th>
                 <th>Pro<br>Number</th>
                 <th>Freight<br>Carrier</th>
                 <th>Claim<br>Amount</th>
                 <th>Freight<br>Claimed</th>
                 <th>Total<br>Claim</th>
                 <th>Amount<br>Paid</th>
                 <th>Amount<br>Due</th>
                 <th>Status</th>
                 <th>Ship<br>Date</th>
                 <th>Received<br>Date</th>
                 <th>Claim<br>Type</th>
                 <th>Created<br>Aging</th> 
                 <th>Filed<br>Aging</th>
                </tr> 
                <tr id="filterrow">
                  <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th> 
                 <th></th>
               </tr> 
         </thead>
        
         <tbody>
                
         </tbody>
        </table>
     </form>
    
    <script type="text/javascript">
    var trHTML = '';            //** Global variable to store TR payable or order data in getChildDetail function.
    var thHTML = '';            //** Global variable to store TH payable or order data in getChildDetail function.
    var childHeaderLabel = '';  //** Global variable to store payable or order label in getChildDetail function.
    
    //Start - document.ready  
    $(document).ready(function() {
    
         // Setup - add a text input to each header cell
         $('table.display thead tr#filterrow th:gt(0)').each( function () {
           $(this).html( '<input type="text" size="1" onclick="stopPropagation(event);" placeholder="Search" />' );
         });
         
        // Apply the filter
         $("table.display thead input").on( 'keyup change', function () {
             table
                 .column( $(this).parent().index()+':visible' )
                 .search( this.value )
                 .draw();
         } );
    
        var table = $('table.display' ).DataTable( {
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]], 
            order: [[ 1, "desc" ]],
            pageLength: 15,
            dom: 'Rlfrtip',
            pagingType: "full_numbers",
            language: {search: "Table Search: "},
            processing: true,
            serverSide: true,
            ajax: 'FreightClaims/ssp_FreightClaimManagement.php',
            columns: [
                      { data: "claim_number_link"},
                      { data: "location" },
                      { data: "department_name" },
                      { data: "vendor_customer" },
                      { data: "pro_number" },  
                      { data: "carrier_name"},
                      { data: "claim_amount" },
                      { data: "freight_claim_amount" },   
                      { data: "total_claim_amount"},
                      { data: "amount_paid" },
                      { data: "amount_due" },
                      { data: "status" },
                      { data: "ship_date"  },
                      { data: "received_date" },
                      { data: "claim_type" },
                      { data: "created_age" },
                      { data: "filed_age" }
                     ],
             select: {
                       style:    'os',
                       selector: 'td:first-child'
                      },
             colReorder: true,
             orderCellsTop: true,
        });//END .dataTable    
    
        table.columns().iterator( 'column', function (ctx, idx) {
                $( table.column(idx).header() ).append('<span class="sort-icon"/>');
        } );
       
    } );//END $(document).ready(function() 
    
    //*************************************** 
    function stopPropagation(evt) {
        if (evt.stopPropagation !== undefined) {
            evt.stopPropagation();
        } else {
            evt.cancelBubble = true;
        }
    } 
    
    function submitform()  //Used to reload form
    {
       document.FC_Loookup.submit();
    }
    </script>
    
  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946
    edited December 2020 Answer ✓

    Best as I can gather from your code you are loading the initial Datatable with this:

    $('#tabContent_0').load('FreightClaims/FreightClaimManagementTest.php?viewType=live');
    

    The button click calls this function:

    function loadTabContent(url, tabLabel){
     
        nextTabNumber++;
        tabNumber++;
     
        tabID = 'tab_'+ nextTabNumber;
        tabContentID = 'tabContent_'+ nextTabNumber;
        tabContentHREF = '#tabContent_'+ nextTabNumber;
     
        $("<li id='"+ tabID +"' class='nav-item'></li>" ).appendTo( "#tabs" );
        $("<a href='"+ tabContentHREF +"' class='nav-link' data-toggle='tab'><button  id='"+ tabNumber +"' class='close' type='button' onclick='closeTab(this.id)'>x</button> "+ tabLabel +" </a>").appendTo("#"+ tabID +"" );
     
        $("<div id='"+ tabContentID +"' class='container-fluid tab-pane fade'>" ).appendTo( "#tabContent" );
         
        $("#"+ tabContentID +"" ).load(url);
    }
    

    Which loads another Datatable. You are using this selector for the Datatables init:

    var table = $('table.display' ).DataTable( { ... } )`
    

    This will find both the original table and the new one. You are getting the reinitialization error with the original table. There are many ways you can handle this. Here are a couple suggestions:

    • Load all of the tabs with all of the tables and init Datatables once when initially loading the Home Page.
    • Use a unique id for each table and change the selector used when initializing Datatables to that particular id.

    These options will require restructuring your code somewhat which will be based on your full solution and requirements which aren't Datatables specific.

    Another option is to change the FreightClaimManagementTest.php script to use jQuery each(), or your preferred method, to loop through all of the elements that are returned with the $('table.display' ) selector. Check each one to see if its a Datatable using $.fn.dataTable.isDataTable() and if not initialize it.

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Got it Kevin, I will need to use a unique ID. I will play around with that technique.
    Thank you for you suggestions.

This discussion has been closed.