Error destroying table and re-create.

Error destroying table and re-create.

drafenousdrafenous Posts: 6Questions: 2Answers: 0
edited November 2018 in Free community support

Hello friends,
I have some difficulties in developing my project, from which I can not destroy a table to create again with other columns and other data.

I can generate the table on the first try, but when I change the type of report I want to generate, because it has fewer columns than the initial one, it ends up generating error and does not exchange the data.

I'll be posting some screenshots about this:

Initial table:

Table with fewer columns:

What it was to show in the table with fewer columns:

My code:

$('#searchRel').on('click', function(e){
  
  if( $('#inputAteRel').val() !== '' &&  $('#inputDeRel').val() !== ''){
    e.preventDefault();

    $('#relName').html($('#nameOfRel').val());
    
    // filter
    var src = '';
    var col = [];
    var colDefs = [];
    var nameOfRel = $('#nameOfRel').val();
    if (nameOfRel == 'Ligações por Fila') {
        //headers = ['Fila', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '%Atend.', '%Não Atend.', '%Aband.'];
    }
    else if (nameOfRel == 'SLA por Fila'){
        //headers = ['Atendidas em até x Seg.', 'Atendidas', 'Não Atendidas', '%Atendidas', '%Não Atendidas', 'SLA'];
    }
    else if (nameOfRel == 'Ligações por Mês'){
      //headers = ['Mês', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '% Atend.', '%Não Atend.', '%Aband.'];
      src = 'timeCalls.months_calls';
      col = [{"title": "Mês", "data": "month", 'targets': 0},
              {"title": "Receb", "data": "receive", 'targets': 1},
              {"title": "Atend", "data": "awnsers", 'targets': 2},
              {"title": "Não Atend.", "data": "notAnswes", 'targets': 3},
              {"title": "Aband.", "data": "abandons", 'targets': 4},
              {"title": "Transf.", "data": "transfers", 'targets': 5},
              {"title": "Logins", "data": "logins", 'targets': 6},
              {"title": "Logoffs", "data": "logoffs", 'targets': 7},
              {"title": "Espera Média", "data": "avarege_wait_time", 'targets': 8},
              {"title": "Tempo Médio", "data": "avarege_conversation_time", 'targets': 9},
              {"title": "Atend.", "data": "porcentage_answers", "className": "porcentage", 'targets': 10},
              {"title": "Não Atend.", "data": "porcentage_notAnswers", "className": "porcentage", 'targets': 11},
              {"title": "Aband.", "data": "porcentage_abandons", "className": "porcentage", 'targets': 12}]
    }
    else if (nameOfRel === 'Ligações por Semana'){
        //headers = ['Semana', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '%Atend.', '%Não Atend.', '%Aband.'];
        src = 'timeCalls.week_calls';
    }
    else if (nameOfRel == 'Ligações por Dia'){
        tableId = 'ligDiaTable';
        src = 'timeCalls.days_calls';
        col = [{"title": 'Dia', 'data': 'day', 'targets': 0}, 
                {"title": 'Receb', 'data': 'receive', 'targets': 1}, 
                {"title": 'Atend.', 'data': 'awnsers', 'targets': 2}, 
                {"title": 'Não Atend.', 'data': 'notAnswes', 'targets': 3}, 
                {"title": 'Aband.', 'data': 'abandons', 'targets': 4}, 
                {"title": 'Transf.', 'data': 'transfers', 'targets': 5}, 
                {"title": 'Logins', 'data': 'logins', 'targets': 6}, 
                {"title": 'Logoffs', 'data': 'logoffs', 'targets': 7}, 
                {"title": 'Espera Média', 'data': 'avarege_wait_time', 'targets': 8}, 
                {"title": 'Tempo Médio', 'data': 'avarege_conversation_time', 'targets': 9}, 
                {"title": 'Atend.', 'data': 'porcentage_answers', 'className': 'porcentage', 'targets': 10}, 
                {"title": 'Não Atend.', 'data': 'porcentage_notAnswers', 'className': 'porcentage', 'targets': 11}, 
                {"title": 'Aband.', 'data': 'porcentage_abandons', 'className': 'porcentage', 'targets': 12}]
    }
    else if (nameOfRel == 'Ligações por Hora'){
      //headers = ['Hora', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '%Atend.', '%Não Atend.', '%Aband.'];
      src = 'timeCalls.hours_calls';
    }
    else if (nameOfRel === 'Ligações Atendidas'){
        src = 'answers_calls';
        col = [{'title': 'Agente', 'data': 'agent', 'targets': 0}, 
                {'title': 'Receb', 'data': 'receive', 'targets': 1},
                {'title': 'Complet', 'data': 'answer', 'targets': 2}, 
                {'title': 'Transf', 'data': 'tranfer', 'targets': 3}, 
                {'title': 'Chamad.', 'data': 'percentage_calls', 'className': 'porcentage', 'targets': 4}, 
                {'title': 'Tempo Convers.', 'data': 'time_conversation', 'targets': 5}, 
                {'title': 'Tempo Total', 'data': 'percentage_time', 'className': 'porcentage', 'targets': 6}, 
                {'title': 'Tempo Med. Convers.', 'data': 'average_conversation_time', 'targets': 7}, 
                {'title': 'Tempo Até Atend./Aband.', 'data': 'avarege_abandon_time', 'targets': 8}, 
                {'title': 'Tempo Med. Espera', 'data': 'avarege_wait_time', 'targets': 9}, 
                {'title': 'Maior Tempo Espera', 'data': 'high_wait_time', 'targets': 10}]
    }
    else if (nameOfRel === 'Ligações Não Atendidas'){
        src = 'notAnswers_calls';
        col = [{"title": "Fila", "data": "queue", 'targets': 0},
                {"title": "Total", "data": "receive", 'targets': 1},
                {"title": "Abandonadas", "data": "abandon", 'targets': 2},
                {"title": "Não Atendidas", "data": "notAnswer", 'targets': 3},
                {"title": "Chamadas", "data": "porcentage", "className": "porcentage", 'targets': 4}];
    }
    else if (nameOfRel == 'Ligações Abandonadas'){
        src = 'graphics.abandon.details';
        col = [{'title': 'Data', 'data': 'date', 'targets': 0},
               {'title': 'Numero', 'data': 'number', 'targets': 1},
               {'title': 'Tempo para Abandono', 'data': 'time', 'targets': 2}]
    }
    else if (nameOfRel == 'Ligações Transferidas'){
        src = 'graphics.tranfer.details';
        col = [{'title': 'Data', 'data': 'date', 'targets': 0},
                {'title': 'Numero', 'data': 'number', 'targets': 1},
                {'title': 'Origem', 'data': 'origin', 'targets': 2},
                {'title': 'Destino', 'data': 'destination', 'targets': 3}]
    }

    var data = {'src': src, 'col': col, 'colDefs': colDefs, 'dtPick': {'date_start': $('#inputDeRel').val(), 'date_end': $('#inputAteRel').val()}};

    // datatable header
    var theader = [];
    $(data.col).each(function(index, item){
      theader.push(item.title);
      var defs = {'title': item.title, 'targets': item.targets, 'visible': true};
      colDefs.push(defs);
    });

    var tHead = `<tr>
                    ${theader.map((th) => {
                        return '<th>'+th+'</th>';
                    }).join()}
                </tr>`;
    
    $('#tHead').html(tHead);
    $('#rel-chamadas').DataTable().destroy();
    // load datatable
    dtResults(data);

    // end
    $("html, body").animate({ scrollTop: $(document).height() }, "slow");
    $('#divRel').slideDown("slow");
    $.fn.dataTable.ext.errMode = 'none';
  };
});

function dtResults(data){
  $('#rel-chamadas').DataTable({
      "destroy": true,
      retrieve: true,
      dom: 'Bfrtip',
      buttons: [
          'excel', 'pdf'
      ],
      "ordering": false,
      "language":{
          "sEmptyTable": "Nenhum registro encontrado",
          "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
          "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
          "sInfoFiltered": "(Filtrados de _MAX_ registros)",
          "sInfoPostFix": "",
          "sInfoThousands": ".",
          "sLengthMenu": "_MENU_ resultados por página",
          "sLoadingRecords": "Carregando...",
          "sProcessing": "Processando...",
          "sZeroRecords": "Nenhum registro encontrado",
          "sSearch": "Pesquisar",
          "oPaginate": {
              "sNext": "Próximo",
              "sPrevious": "Anterior",
              "sFirst": "Primeiro",
              "sLast": "Último"
          },
          "oAria": {
              "sSortAscending": ": Ordenar colunas de forma ascendente",
              "sSortDescending": ": Ordenar colunas de forma descendente"
          }
      },
      "ajax": {
        "url": "<?= base_url('relatorios/aux_front'); ?>",
        "dataSrc": data.src,
        "dataType": 'json',
        "data": data.dtPick,
        "type": 'post',
        "error": function(response){
          console.error(response);
        }
      },
      "columns": data.col,
      "columnDefs": data.colDefs
  });
}

EDIT: Updated to use Markdown Code formatting.

Replies

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    What is the error you are getting?

    It looks like you are manipulating the table before destroying it:

        $('#tHead').html(tHead);
        $('#rel-chamadas').DataTable().destroy();
    

    If you have a Datatable you should destroy it before changing it. Also you don't need to build and append the header to the DOM. The columns.title option will take care of that.

    My suggestion would be to try this:

    $('#rel-chamadas').DataTable().destroy();
    $('#rel-chamadas').empty();
    // load datatable
    dtResults(data);
    
    

    The jQuery empty method should empty the table. Depending on when you are doing this you may want to use the $.fn.dataTable.isDataTable() to make sure the datatable exists before destroying it.

    Kevin

  • drafenousdrafenous Posts: 6Questions: 2Answers: 0

    @kthorngren works fine!
    Thanks alot.

This discussion has been closed.