Filter table data by a separate input type="text"

Asked

Viewed 43 times

0

I have a table that uses Datatables, and for me to filter its data, I use an input that is outside the table code, a separate input. It turns out that recently I implemented the server-side Processing in my Datatables, to load the records faster, and this filter function in the table stopped working, I don’t know exactly why, it is below my code:

inserir a descrição da imagem aqui

// Código que era para direcionar o filtro da tabela ao input #filterbox
$("#filterbox").keyup(function() {
dataTable.search(this.value).draw();
});

 

index php.

<!-- INPUT que será usado para filtrar os dados da tabela -->
<input type="text" name="filterbox" id="filterbox">

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>First name</th>
            <th>Last name</th>
            <th>Position</th>
            <th>Office</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>ID</th>
            <th>First name</th>
            <th>Last name</th>
            <th>Position</th>
            <th>Office</th>
        </tr>
    </tfoot>
</table>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('#example').DataTable( {
            "sDom": "<'row'<'col-sm-12'tr>>" + "<'card-footer p-0 pt-1'<'row'<'col-6'l><'col-6'p>>>",
            "lengthMenu": [[10, 25, 50, 100, -1], ["Exibir 10", "Exibir 25", "Exibir 50", "Exibir 100", "Exibir Todos"]],
            "oLanguage": {
            "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_",
            "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",
            },
          },
            "processing": true,
            "serverSide": true,
            "ajax": "server.php"
        } );

        // Código que era para direcionar o filtro da tabela ao input #filterbox
        $("#filterbox").keyup(function() {
        dataTable.search(this.value).draw();
        });

    } );
</script>
</body>

 ssp.class.php

/**
 * Searching / Filtering
 *
 * Construct the WHERE clause for server-side processing SQL query.
 *
 * NOTE this does not match the built-in DataTables filtering which does it
 * word by word on any field. It's possible to do here performance on large
 * databases would be very poor
 *
 *  @param  array $request Data sent to server by DataTables
 *  @param  array $columns Column information array
 *  @param  array $bindings Array of values for PDO bindings, used in the
 *    sql_exec() function
 *  @return string SQL where clause
 */
static function filter ( $request, $columns, &$bindings )
{
    $globalSearch = array();
    $columnSearch = array();
    $dtColumns = self::pluck( $columns, 'dt' );

    if ( isset($request['search']) && $request['search']['value'] != '' ) {
        $str = $request['search']['value'];

        for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
            $requestColumn = $request['columns'][$i];
            $columnIdx = array_search( $requestColumn['data'], $dtColumns );
            $column = $columns[ $columnIdx ];

            if ( $requestColumn['searchable'] == 'true' ) {
                if(!empty($column['db'])){
                    $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                    $globalSearch[] = "`".$column['db']."` LIKE ".$binding;
                }
            }
        }
    }

    // Individual column filtering
    if ( isset( $request['columns'] ) ) {
        for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
            $requestColumn = $request['columns'][$i];
            $columnIdx = array_search( $requestColumn['data'], $dtColumns );
            $column = $columns[ $columnIdx ];

            $str = $requestColumn['search']['value'];

            if ( $requestColumn['searchable'] == 'true' &&
             $str != '' ) {
                if(!empty($column['db'])){
                    $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                    $columnSearch[] = "`".$column['db']."` LIKE ".$binding;
                }
            }
        }
    }

    // Combine the filters into a single string
    $where = '';

    if ( count( $globalSearch ) ) {
        $where = '('.implode(' OR ', $globalSearch).')';
    }

    if ( count( $columnSearch ) ) {
        $where = $where === '' ?
            implode(' AND ', $columnSearch) :
            $where .' AND '. implode(' AND ', $columnSearch);
    }

    if ( $where !== '' ) {
        $where = 'WHERE '.$where;
    }

    return $where;
}

1 answer

0

Good morning, try it this way to see if it works:

$('#filterbox').on( 'keyup', function () {
    table
        .search( this.value )
        .draw();
} );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.