Why my datatable doesn't load its configuration when the page loads ?

Why my datatable doesn't load its configuration when the page loads ?

lucasvavonlucasvavon Posts: 11Questions: 4Answers: 0

When I load my page, I have to interact with the table (a search for example), so that the table is correctly set up according to the imposed sorting or even to be able to sort it with the buttons provided for this purpose at the head of the table.

page before interaction

page after interaction

and the code corresponding to the page :

JavaScript :

function loadCustomers() {
    var datas = {
        path: "customer_mail_alert_stock",
        page: "customer_mail_alert_stock_list",
        bJSON: 1
    }
    $.ajax({
            type: "POST",
            url: "route.php",
            async: true,
            data: datas,
            dataType: "json",
            cache: false
        })
        .done(function(result) {
            var iCustomer = 0;
            aOfCustomers = [];
            path_admin = result.path_admin

            for (var ligne in result) {
                if (ligne != 'path_admin') {
                    aOfCustomers[iCustomer] = [];
                    aOfCustomers[iCustomer]["id_customer"] = result[ligne]["id_customer"];
                    aOfCustomers[iCustomer]["email"] = result[ligne]["email"];
                    aOfCustomers[iCustomer]["id_product"] = result[ligne]["id_product"];
                    aOfCustomers[iCustomer]["name"] = result[ligne]["name"];
                    aOfCustomers[iCustomer]["lastname"] = result[ligne]["lastname"];
                    aOfCustomers[iCustomer]["firstname"] = result[ligne]["firstname"];
                    aOfCustomers[iCustomer]["id_product_attribute"] = result[ligne]["id_product_attribute"];
                    aOfCustomers[iCustomer]["date_creation"] = result[ligne]["date_creation"];
                    aOfCustomers[iCustomer]["product_name"] = result[ligne]["product_name"];

                    iCustomer++;
                }
            }

            // INIT DATATABLE
            constructTableCustomers();
            // reload datatable configuration
            tablesCustomers = $('#datatable').DataTable(configuration);
            $('#divModalLoading').hide();

        })
        .fail(function(err) {
            // error
            alert('error : ' + err.status);
        });
}

function constructTableCustomers() {
    var i;
    // tableau datatable
    var sHTML = "";
    sHTML += '<table id="datatable" class="table table-striped table-bordered" style="width:100%">';
    sHTML += "<thead>";
    sHTML += "<tr>";
    sHTML += '<th style="text-align:center;"><input type="checkbox" id="bulk_action_select_all" onclick="selectAllCustomers()"></th>';
    sHTML += "<th>ID CLIENT </th>";
    sHTML += "<th style='padding-right: 15px !important;'>EMAIL CLIENT</th>";
    sHTML += "<th>ID PRODUIT</th>";
    sHTML += "<th>NOM PRODUIT</th>";
    sHTML += "<th>ATTRIBUT</th>";
    sHTML += "<th>ID ATTRIBUT</th>";
    sHTML += "<th>NOM</th>";
    sHTML += "<th>PRENOM</th>";
    sHTML += "<th>DATE DE CREATION</th>";
    sHTML += "</tr>";
    sHTML += "</thead>";
    sHTML += "<tbody>";

    // pour chaque ligne de résultat, construire la ligne dans datatable
    for (i = 0; i < aOfCustomers.length; i++) {

        sHTML += '<tr style="text-align:center;">';

        sHTML += '<td>' + '<input type="checkbox" class="select-checkbox" id="checkbox_' + i + '">' + '</td>';

        sHTML += `<td><a href='/${path_admin}/index.php/sell/customers/${aOfCustomers[i]["id_customer"]}/view?_token=${tokenAdminProducts}' target="_blank">${aOfCustomers[i]["id_customer"]}</a></td>`;

        sHTML += `<td><a href='/${path_admin}/index.php/sell/customers/${aOfCustomers[i]["id_customer"]}/view?_token=${tokenAdminProducts}' target="_blank">${aOfCustomers[i]["email"]}</a></td>`;

        sHTML += `<td><a href='/${path_admin}/index.php/sell/catalog/products/${aOfCustomers[i]["id_product"]}?_token=${tokenAdminProducts}' target='_blank'>${aOfCustomers[i]["id_product"]}</a></td>`;

        sHTML += "<td>" + aOfCustomers[i]["product_name"] + "</td>";

        sHTML += "<td>" + aOfCustomers[i]["name"] + "</td>";

        sHTML += "<td>" + aOfCustomers[i]["id_product_attribute"] + "</td>";

        sHTML += "<td>" + aOfCustomers[i]["lastname"] + "</td>";

        sHTML += "<td>" + aOfCustomers[i]["firstname"] + "</td>";

        sHTML += "<td>" + aOfCustomers[i]["date_creation"] + "</td>";

        sHTML += '</tr>';
    }
    sHTML += "</tbody>";
    sHTML += "</table>";
    $('#customer_mail_alert_stock_table').html(sHTML);
}

const configuration = {
    "stateSave": false,
    "order": [
        [9, "desc"],
        [3, "asc"],
        [1, "asc"]
    ],
    "pageLength": 25,
    "pagingType": "simple_numbers",
    "searching": true,
    "search": {
        'search': product
    },
    "lengthMenu": [
        [10, 25, 50, 100, 250, -1],
        [10, 25, 50, 100, 250, "Tous"]
    ],
    "language": {
        "info": "Affichage des lignes _START_ &agrave; _END_ sur _TOTAL_ r&eacute;sultats au total",
        "emptyTable": "Aucun r&eacute;sultat disponible",
        "lengthMenu": "Affichage de _MENU_ r&eacute;sultats",
        "search": "Rechercher : ",
        "zeroRecords": "Aucun r&eacute;sultat trouv&eacute;",
        "paginate": {
            "previous": "Pr&eacute;c&eacute;dent",
            "next": "Suivant"
        },
        "sInfoFiltered": "(filtr&eacutes &agrave; partir de _MAX_ r&eacute;sultats au total)",
        "sInfoEmpty": "Aucun r&eacute;sultat disponible"
    },

    dom: 'Bflrtip',
    scrollX: true,
    buttons: [{
        extend: 'csv',
        text: 'CSV selected',
        exportOptions: {
            columns: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            modifier: {
                selected: true
            }
        }
    }],

    "retrieve": true,
    "responsive": true,
    "autoWidth": false
};

$(document).ready(function() {
    loadTokenAdminProducts();
    loadCustomers();
    loadDocumentRoot();
});

HTML :

<div class="x_content">
    <div class="row">
        <div class="col-sm-12">
            <div class="card-box table-responsive" id="customer_mail_alert_stock_table"> </div>
        </div>
    </div>
</div>

Don't hesitate to tell me if you have any idea. Thanks in advance !

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974
    edited January 2022

    Your code snippet seems reasonable. Nothing obvious stands out as an issue. A guess is that Datatables is initialized with a different configuration object on page load. Can you post a link to your page or a test case replicating the issue so we can help debug?
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Do you get errors in the browser's console?

    Kevin

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    In order to help debug we will need to see a running example of the problem. Just having the code is not enough to debug.

    I would start by putting a debugger break point just before the Datatables initialization on line 40 above to see what happens.

    Kevin

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    looks like loadTokenAdminProducts() has some asynchronous code. Maybe you need to call loadCustomers() at the end of the .done() function in case there is a dependency on loadTokenAdminProducts() before the first initialization of Datatables.

    Kevin

  • lucasvavonlucasvavon Posts: 11Questions: 4Answers: 0
    edited January 2022

    i share wrong code, im sorry

    here's the good one : https://jsbin.com/tenisagede/edit?js,output

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    Uncaught TypeError: Cannot set properties of undefined (setting 'select')

    My guess is you are loading select.js before datatables.js. Order is important. Use the Download Builder to generate the library files in the proper order. Or make sure to load select.js after datatales.js.

    Kevin

  • lucasvavonlucasvavon Posts: 11Questions: 4Answers: 0

    i paste CDN in Html right ?

  • lucasvavonlucasvavon Posts: 11Questions: 4Answers: 0
    edited January 2022

    now i can see datatable checkboxes but they are not clickable;

    my following configuration is correct ?

    dom: 'Bflrtip',
    buttons: [
        {
            extend: 'csv',
            exportOptions: {
                orthogonal: 'sort'
            }
        }        
    ],
    columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
    select: {
        style:    'os',
        selector: 'td:first-child'
    },
    
  • lucasvavonlucasvavon Posts: 11Questions: 4Answers: 0
    edited January 2022

    i can see :

    If you load your content from ajax then you will want to use the defaultContent option in your columnDefs.

    {
        targets: 0,
        data: null,
        defaultContent: '',
        orderable: false,
        className: 'select-checkbox'
    }
    

    so, i haver add this, its correct ?

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974
    Answer ✓

    now i can see datatable checkboxes but they are not clickable;

    Please provide a test case or link to your page showing the issue so we can help debug. Posting code snippets is not enough for us to know the problem.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

Sign In or Register to comment.