Duplicate thead and unnecessary scrolls

Duplicate thead and unnecessary scrolls

XanaxLolXanaxLol Posts: 3Questions: 1Answers: 0

When I use responsiveness, I have no errors,then as soon as I try to make fixedCoulmns, a new thead is added to tbody,and thus there are two theads.Unnecessary scrolls are also added.I use bootstrap4

html
Here is the basic layout of the table for further interaction with it.

<table class="mx-auto table table-striped table-bordered data-report" style="width:100%">
  <thead>
    <tr></tr>
  </thead>
 </table>

Jq
With the help of data that came through ajax(data_report.php), I form td to tr.

$.ajax({
    url: '../../../assets/php/data_report.php',
    type: 'POST',
    dataType: 'json',
    data: {
        json: localStorage.getItem('info_reports')
    },
    success: function (data) {
        let array = data;
        array.forEach(e => {
            if (e === 'id') {
                $('.data-report').find('thead').find('tr').append(
                    `<th class="text-center align-baseline">${e}</th>`
                )
            } else {
                $('.data-report').find('thead').find('tr').append(
                    `<th class="text-center align-baseline vis-tabs">${e}</th>`
                );
            }
        });
        $('.data-report').find('thead').find('tr').append(
            `<th class="text-center align-baseline not-visable" style:"width:100%;"></th>`
        );

PHP(data_report.php)

<?php
    session_start();
    require_once('mysql.php');

    $report_id = json_decode($_POST['json'], true)[0][0];
    
    $_SESSION['report']['id'] = $report_id;

    $sql = 'SELECT fields FROM reports WHERE id = ?';
    $select = $pdo->prepare($sql);
    $select->execute( [$report_id] );
    $from_reports = $select->fetch(PDO::FETCH_ASSOC);

    // $from_reports = mysqli_fetch_assoc(mysqli_query($mysql, "SELECT `fields` FROM `reports` WHERE `id` = '$report_id'"));
    // $from_filled_reports = mysqli_fetch_all(mysqli_query($mysql, "SELECT `filled_fields`, (SELECT firstname from users WHERE users.id = filled_reports.id_user), (SELECT lastname from users WHERE users.id = filled_reports.id_user) FROM `filled_reports` WHERE `id_report` = '$report_id'"));

    $first = ['id', 'ФИО', 'Название организации', 'Название отдела', 'Роль', 'Телефон', 'Дата ввода информации'];

    $fields = json_decode($from_reports['fields'], true);

    foreach ($fields as $field) {
        array_push($first, $field["name_pole"]);
    }
    
    echo json_encode($first);

<?php
>
?>


Datatables

table_report = $('.data-report').DataTable({
            "pagingType": "full_numbers",
            responsive: true,
            // scrollX: true,
            // // scrollY: 200,
            // scrollCollapse: true,
            // /* paging: false, */
            // fixedColumns: true,
            // fixedColumns: {
            //   leftColumns:0,
            //   rightColumns:1,
            // },
            dom: 'Bfrtip',
            "processing": true,
            "serverSide": true,
            "ajax": "../../../assets/php/data_report_json.php",
            lengthMenu: [
                [10, 25, 50, -1],
                ['10 строк', '25 строк', '50 строк', 'Показать все']
            ],
            // select:{
            //     style:'os',
            //     selector:'td:not(:last-child)'
            // },
            "language": {
                "paginate": {
                    "first": "Первая",
                    "previous": "Предыдущая",
                    "next": "Следующая",
                    "last": "Последняя"
                },
                "aria": {
                    "sortAscending": ": активировать для сортировки столбца по возрастанию",
                    "sortDescending": ": активировать для сортировки столбца по убыванию"
                },
                "select": {
                    "rows": {
                        "_": "Выбрано записей: %d",
                        "0": "Кликните по записи для выбора",
                        "1": "Выбрана одна запись"
                    }
                },
                "processing": `<div class="preloader" id="page-preloader">
                          <div class="loader_one">
                            <div class="loader_two"></div>
                          </div>
                        </div>`,
                "search": "Поиск:",
                "lengthMenu": "Показать _MENU_ записей",
                "info": "Записи с _START_ до _END_ из _TOTAL_ записей",
                "infoEmpty": "Записи с 0 до 0 из 0 записей",
                "infoFiltered": "(отфильтровано из _MAX_ записей)",
                "infoPostFix": "",
                "loadingRecords": "Загрузка записей...",
                "zeroRecords": "Записи отсутствуют.",
                "emptyTable": "В таблице отсутствуют данные",
                buttons: {
                    pageLength: {
                        _: "Показать %d строк"
                    }
                }
            },
            "columnDefs": [
                // {
                //     "defaultContent": "<b class='red'>не указано<i></i></b>",
                //     "targets": countRows
                // },
                {
                    "targets": [0],
                    // visible: false,
                    "orderable": false,
                    "searchable": false,
                },
                // {
                //     "targets": offSrchOrdbl,
                //     "orderable": false,
                //     "searchable": false,
                // },
                {
                    "title": "Действие",
                    "targets": -1,
                    "orderable": false,
                    "searchable": false,
                    "className": "text-center",
                    render: function (data) {
                        return `
                                <div class="d-flex justify-content-center">
                                <button class="btn btn-sm btn-outline-success view-rep mr-50">Просмотр</button>
                                <button class="btn btn-sm btn-outline-danger clear-rep">Очистка</button>
                                </div>
                                `;
                    },
                }

            ],
            buttons: [
                {
                    extend: 'pageLength',
                },
                {
                    extend: 'excel',
                    extension: '.xlsx',
                    exportOptions: {
                        columns: ".vis-tabs",
                    }
                }]

        });


Replies

  • kthorngrenkthorngren Posts: 21,173Questions: 26Answers: 4,923
    edited October 2020

    Looks like you are using the default Datatables styling instead of the Datatables Bootstrap4 styling as shown in this example. You can use the Download Builder to get the proper JS and CSS files for BS4, Datatables and the extensions. This may be part of the issue.

    FicxedColumns clones the thead during initialization. The other thing I would look at is to make sure the thead is built before Datatables is initialized. Are you initializing Datatables after the you build the header in the Ajax success function in your second snippet?

    If you still need help please provide a link to your page or a running test case replicating the issue so we can help debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • kthorngrenkthorngren Posts: 21,173Questions: 26Answers: 4,923

    Additionally this comment can be found in the Compatibility matrix if you hover over the intersection of Responsive and FixedColumns:

    FixedColumns and Responsive effectively try to solve the same issue - showing more data than can fit on screen. If Responsive is active, then there is no scrolling, and therefore no need for FixedColumns.

    Kevin

This discussion has been closed.