DataTables double ajax request

DataTables double ajax request

DeleteDelete Posts: 2Questions: 1Answers: 1

HI.
First DataTables is awsome and works great and fast but i have a strange problem using server processing im getting double ajax request with draw: 1 and draw: 2 parameters. The page that contains DataTables is loaded with ajax. The page contains 4 tables separated in bootstrap tabs. I also use one search field to search in all the tables.When searching everything is fine im getting only 4 ajax requests, only when loading the page im getting 8 double ajax requests.

here is the code for one table. All other tables are the same with different ajax data

$(document).ready(function () {


    $('#isprati tbody').unbind();

    var pocdatum = $('#pocdatum').val();
    var krajdatum = $('#krajdatum').val();

    var selectedUsluga = ($('input[name="usluga"]:checked').serialize());
    var selectedTip = ($('input[name="tip"]:checked').serialize());
    if ($.fn.DataTable.isDataTable("#isprati")) {
        $('#isprati').DataTable().clear().destroy();
    }
    var table1 = $('#isprati').DataTable({
        responsive: {
            details: {
                type: 'column'
            }
        },
        //deferRender: true,
        //pageResize: true,

        autoWidth: false,
        // "processing": true,
        "serverSide": true,
        "order": [[8, "asc"]],
        scrollY: '34vh',
        scrollCollapse: true,
        "pageLength": 100,
        "ajax": {
            url: "/admin/src/nalozi.src.php", // json datasource
            type: "post",  // method  , by default get
            data: {
                type: 1,
                checkUsluga: selectedUsluga,
                checkTip: selectedTip,
                nalogType: 'Да се испрати екипа',
                enddate: krajdatum,
                startdate: pocdatum
            }
        },
        columns: [
            {"data": null, "defaultContent": "", className: 'control', orderable: false, targets: 0},
            {"data": "1", targets: 1},
            {"data": "2", targets: 2},
            {"data": "3", targets: 3},
            {"data": "4", targets: 4},
            {"data": "5", targets: 5},
            {"data": "6", targets: 6},
            {"data": "7", targets: 7, className: 'none'},
            {"data": "8", targets: 8}
        ],
        buttons: [{
            text: 'Прати Екипа',
            className: 'btn btn-success btn-xs',
            action: function (e, dt, node, config) {
                var data = table1.rows('.selected').data().toArray();
                var newarray = [];
                for (var i = 0; i < data.length; i++) {
                    newarray.push(data[i][1]);
                }

                var sData = newarray.join();
                $.ajax({
                    type: 'post',
                    url: '/admin/src/nalogDetail.src.php',
                    data: {
                        nid: data[0]
                    },
                    success: function (data) {
                        $("#nbody").html('');
                        $("#nbody").html(data);
                        $("#nnaslo").html('');
                        $("#nnaslo").html('<button type="button" class="close" data-dismiss="modal">&times;</button><h5 id="nalogIDbr" data-id="' + nid + '" class="modal-title">Детали за налог бр: ' + nid + '</h5>');
                        $('#nalog-detail').modal("show");
                    }
                })

            },
            init: function (api, node, config) {
                $(node).removeClass('dt-button');
                $(node).removeClass('btn-default');
                $(node).addClass('pratiEkipa');
            }
        }],
        dom: 'B' +
        '<<"row"><"col-md-12"rt>>' +
        '<<"row"><"col-md-3"i><"col-md-9"p>>',
        "infoCallback": function (settings, start, end, max, total, pre) {
            return "Резултати: " + total;
        },
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            // Bold the grade for all 'A' grade browsers
            if (aData[6] === "Интернет") {
                $('td:eq(6)', nRow).html('<span class="label label-danger" style="font-size: 12px;">Интернет</span>');
            }
            if (aData[6] === "Телевизија") {
                $('td:eq(6)', nRow).html('<span class="label label-primary" style="font-size: 12px;">Телевизија</span>');
            }
            if (aData[6] === "Телефонија") {
                $('td:eq(6)', nRow).html('<span class="label label-info" style="font-size: 12px;">Телефонија</span>');
            }
            if (aData[6] === "Дигитална") {
                $('td:eq(6)', nRow).html('<span class="label label-success" style="font-size: 12px;">Дигитална</span>');
            }
            if (aData[6] === "Инфо Центар") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Инфо центар</span>');
            }
            if (aData[6] === "Канцеларија 4") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Канцеларија 4</span>');
            }
            if (aData[6] === "Канцеларија 5") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Канцеларија 5</span>');
            }
            if (aData[6] === "Канцеларија 6") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Канцеларија 6</span>');
            }
            if (aData[6] === "Канцеларија 7") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Канцеларија 7</span>');
            }
            if (aData[6] === "Канцеларија 8") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Канцеларија 8</span>');
            }
            if (aData[6] === "Наплатен центар") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Наплатен центар</span>');
            }
            if (aData[6] === "Шефови на екипи") {
                $('td:eq(6)', nRow).html('<span class="label label-default" style="font-size: 12px;">Шефови на екипи</span>');
            }


            if (aData[5] === "Дефект") {
                $('td:eq(5)', nRow).html('<span class="label label-danger" style="font-size: 12px;">Дефект</span>');
            }
            if (aData[5] === "Нов приклучок") {
                $('td:eq(5)', nRow).html('<span class="label label-primary" style="font-size: 12px;">Нов приклучок</span>');
            }
            if (aData[5] === "Исклучување") {
                $('td:eq(5)', nRow).html('<span class="label label-success" style="font-size: 12px;">Исклучување</span>');
            }
        },
        "language": {
            "sProcessing": "Процесирање...",
            "sLengthMenu": "_MENU_ записи",
            "sZeroRecords": "Не се пронајдени записи",
            "sEmptyTable": "Нема податоци во табелата",
            "sLoadingRecords": "Вчитување...",
            "sInfo": "_START_ до _END_ од _TOTAL_ записи",
            "sInfoEmpty": "0 до 0 од 0 записи",
            "sInfoFiltered": "(Вкупно _MAX_ записи)",
            "sInfoPostFix": "",
            "sSearch": "Барај",
            "sUrl": "",
            "oPaginate": {
                "sFirst": "Почетна",
                "sPrevious": "Претходна",
                "sNext": "Следна",
                "sLast": "Последна"
            }
        }
    });

   
    $("#tab_filter").unbind();
    $("#tab_filter").keyup(function (e) {
        if (e.keyCode === 13) {
            table1.search(this.value).draw();
          
        }
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        $($.fn.dataTable.tables(true)).DataTable().columns.adjust().responsive.recalc();
    });


    $('#isprati tbody').on('click', 'tr', function () {
        $(this).toggleClass('selected');
    });
    $('#isprati tbody').off('dblclick');

    $('#isprati tbody').on('dblclick', 'tr', function () {
        $('#nalog-detail').unbind();
        var data = table1.row(this).data();
        var nid = data[1];

        $.ajax({
            type: 'post',
            url: '/admin/src/nalogDetail.src.php',
            data: {
                nid: nid,
                allowed: 1
            },
            success: function (data) {
                $("#nbody").html('');
                $("#nbody").html(data);
                $("#nnaslo").html('');
                $("#nnaslo").html('<button type="button" class="close" data-dismiss="modal">&times;</button><h5 id="nalogIDbr" data-id="' + nid + '" class="modal-title">Детали за налог бр: ' + nid + '</h5>');
                $('#nalog-detail').modal("show");
            }
        })
    });

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,457Questions: 1Answers: 10,465 Site admin

    Could you link to the page showing the issue please? I don't see what would cause the problem in the above code.

    Allan

  • DeleteDelete Posts: 2Questions: 1Answers: 1
    Answer ✓

    Sorry its not datatables issue i have this problem on other pages i just noticed.
    Thx allan and sorry for wasting your time.

  • kveekvee Posts: 3Questions: 1Answers: 1

    I have the same problem. I found that double ajax call was from responsive.
    Here is my code:

    $('#usersTable').DataTable({
            'autoWidth': false,// prevent rotate screen and checkbox column too wide.
            'dom': '<"table-controls">f<"clearfix">rtip<"clearfix">',
            'columns': [
                {'data': ''},// responsive expand/collapse column
                {'data': 'id'},// checkbox column
                {'data': 'user_login'},
                {'data': 'user_display_name'},
                {'data': 'user_email'},
                {'data': 'groups'},
                {'data': 'status'},
            ],
            'columnDefs': [
                {
                    'className': 'control',
                    'orderable': false,
                    'searchable': false,
                    'targets':   0,
                    'render': function() {
                        return '';// make first column render nothing (for responsive expand/collapse button only).
                    }
                },
                {
                    'searchable': false,// make checkbox column can't search.
                    'orderable': false,// make checkbox column not sortable.
                    'className': 'column-checkbox',
                    'targets': 1,
                    'render': function (data, type, row, meta) {
                        return '<input type="checkbox" name="user_id[]" value="' + $('<div/>').text(row.user_id).html() + '">';
                    }
                },
                {
                    'targets': 3,
                    'render': function(data, type, row, meta) {
                        if (typeof(row.user_display_name) === 'undefined' || (typeof(row.user_display_name) !== 'undefined' && !row.user_display_name)) {
                            return '&mdash;';
                        } else {
                            return row.user_display_name;
                        }
                    }
                },
                {
                    'targets': 5,
                    'render': function() {
                        return '';
                    }
                },
                {
                    'targets': 6,
                    'render': function() {
                        return '';
                    }
                }
            ],
            'order': [],// make sortable icon disappears from first column.
            'orderMulti': false,
    
            'responsive': {
                'details': {
                    'type': 'column'
                }
            },
    
            'processing': true,
            'serverSide': true,
            'searchDelay': 1300,
            'ajax': {
                url: XhrCommon.currentUrlRaw,
                data: function(d) {
                    d.CSRFTOKEN = 'customToken';
                }
            },
        });
    

    Remove those responsive: {...} value and ajax request is just once otherwise it will be double call.

  • allanallan Posts: 63,457Questions: 1Answers: 10,465 Site admin

    Yes - there is a bug in the current release of Responsive causing that I'm afraid. The nightly has it fixed already and it will be in the next release, which should happen this week.

    Allan

  • MignarMignar Posts: 2Questions: 0Answers: 0

    @allan Is the new version out yet? I'm using 1.10.16 and 2.2.1 for responsive and still having this issue. Am I doing something wrong?

    Thanks

  • allanallan Posts: 63,457Questions: 1Answers: 10,465 Site admin

    Could you give me a link to the page showing the issue please? Responsive 2.2.1 should have resolved this.

    Allan

  • MignarMignar Posts: 2Questions: 0Answers: 0

    Thank you for your response @allen ,
    it seemed like I've had caching issues. I've cleared some things and now it works amazingly. Thank you !

This discussion has been closed.