How to redraw a Datatable if a checkbox is checked?

0

Ihavethistableusingdatatable,andIneedtochangetheWHEREoftheselectthatfillsitifthe"View all users" checkbox is checked. I created this function to know if the checkbox is checked, now I need to send this users variable via Ajax to the file that assembles the select and recreate the table bringing all the records, how do I do that?

$('#all_users').click(function(){
  if($(this).is(':checked') ) {
    var users = 'all';
  }
});

Table created

var tabela = $("#lista-dados").DataTable({
 "processing": false,
 "serverSide": true,
 "autoWidth": true,
 "ajax": {
     "type": "POST",
     "data": ws_datatable,
     "url": "./functions/ws_datatable.php"
  },
  "order": [[ 2, "desc" ]],
  "lengthMenu": [[10, 25, 50, 100, 250, 500, -1]],
  "pageLength": 10,
  "bStateSave": true,
  "paging": true,                                
  "dom": "lBfrtipr",
  buttons: []
});
    
asked by anonymous 25.07.2018 / 19:59

2 answers

1

Example

You need to pass a parameter to the server indicating that it wants all users, in case if the parameter "" in user

$('#all_users').click(function () {
    if ($(this).is(':checked')) {
        var users = 'all'; //vamos parasse esse parâmetro no URL
        criarDatatable(users)
    }
});

function criarDatatable(users) {

    //antes de reconstruir a tabela tem que a destruir primeiro (apenas se estiver alterando uma datatable já existente)
    if ($.fn.dataTable.isDataTable('#lista-dados')) {
        tabela = $('#lista-dados').DataTable();
        tabela.destroy();
    }

    var tabela = $("#lista-dados").DataTable({
        "processing": false,
        "serverSide": true,
        "autoWidth": true,
        "ajax": {
            "type": "POST",
            "data": ws_datatable,
            "url": "./functions/ws_datatable.php?users=" + users //parâmetro no URL
        },
        "order": [[2, "desc"]],
        "lengthMenu": [[10, 25, 50, 100, 250, 500, -1]],
        "pageLength": 10,
        "bStateSave": true,
        "paging": true,
        "dom": "lBfrtipr",
        buttons: []
    });
};

//reserved é apenas um exemplo de parâmetro 

criarDatatable('reserved');
    
25.07.2018 / 21:11
0

With the AJAX return, recreate the table with jquery and start the Datatable

JS

<script>
    // com os dados do retorno repreencha o table-wrapper
    $('#table-wrapper').html(
        '<table id="table">
             <thead>
                 <th>Id</th>
                 <th>Nome</th>                
             </thead>
             <tbody>
                 <td>' + data.id + '</td>
                 <td>' + data.nome + '</td>
             </tbody>
        </table>'
    );

    $(document).ready( function () {
        $('#table').DataTable();
    });
</script>
    
25.07.2018 / 20:36