Настраиваемый фильтр данных по столбцам

#jquery #datatable

Вопрос:

У меня возникли некоторые проблемы с пользовательской фильтрацией данных из входного тега только по 1 столбцу. Я думаю, что в моих сценариях может быть конфликт, но не могу понять, где именно. Я попробовал этот код, используя простую таблицу, заполненную в формате html, и он отлично работает. Но когда таблица заполняется из базы данных, она ничего не делает.

Я проверил несколько тем по этой теме, но не смог найти полезного ответа.

Рассмотрим приведенный ниже пример. Таблица заполняется из тестовой базы данных по умолчанию в xampp с помощью php-скрипта.

Главная страница (test.php):

 lt;!doctype htmlgt; lt;html lang="en"gt;  lt;headgt;  lt;!-- Required meta tags --gt;  lt;meta charset="utf-8"gt;  lt;meta name="viewport" content="width=device-width, initial-scale=1"gt;   lt;!-- Bootstrap CSS --gt;  lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"gt;   lt;link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs5/jq-3.6.0/jszip-2.5.0/dt-1.11.3/b-2.0.1/b-colvis-2.0.1/b-html5-2.0.1/r-2.2.9/sb-1.3.0/sp-1.4.0/datatables.min.css"/gt;  lt;script type="text/javascript" src="https://cdn.datatables.net/v/bs5/jq-3.6.0/jszip-2.5.0/dt-1.11.3/b-2.0.1/b-colvis-2.0.1/b-html5-2.0.1/r-2.2.9/sb-1.3.0/sp-1.4.0/datatables.min.js"gt;lt;/scriptgt;  lt;script type="text/javascript" language="javascript" src="test.js"gt;lt;/scriptgt;   lt;titlegt;Custom column filteringlt;/titlegt;  lt;/headgt;  lt;bodygt;  lt;div class="container"gt;    lt;div class="form-group mb-5 mt-3"gt;  lt;label for="customerName"gt;Filter by CustomerNamelt;/labelgt;  lt;input type="text" id="customerName" class="form-control form-control-sm w-25"gt;  lt;/divgt;     lt;div class="panel-heading"gt;lt;h3gt;Customer List:lt;/h3gt;  lt;div class="panel-body pt-2 pb-2"gt;  lt;div class="table-responsive"gt;  lt;table id="customerList" class="table table-striped table-hover"gt;  lt;theadgt;  lt;trgt;  lt;thgt;CustomerID lt;/thgt;  lt;thgt;CustomerNamelt;/thgt;  lt;thgt;Addresslt;/thgt;  lt;thgt;Citylt;/thgt;  lt;thgt;PostalCodelt;/thgt;  lt;thgt;Countrylt;/thgt;  lt;/trgt;  lt;/theadgt;  lt;/tablegt;  lt;/divgt;  lt;/divgt;  lt;/divgt;  lt;/divgt;  lt;!-- Option 1: Bootstrap Bundle with Popper --gt;  lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous"gt;lt;/scriptgt;  lt;/bodygt; lt;/htmlgt;  

Я получаю информацию с помощью Ajax (test.js):

 $(document).ready(function(){  $('#customerList').DataTable({  "processing": true,  "serverSide": true,  "order":[],  "ajax":{  url:"testFetch.php",  type:"POST",  },  "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ],  dom: "lt;'row m-1'lt;'col-sm-12 col-md-2'lgt;lt;'col-sm-12 col-md-4'Bgt;lt;'col-sm-12 col-md-6'fgt;gt;"     "lt;'row m-1'lt;'col-sm-12'trgt;gt;"     "lt;'row m-1'lt;'col-sm-12 col-md-5'igt;lt;'col-sm-12 col-md-7'pgt;gt;",  buttons:[  {extend: 'excel', text: 'Download'}  ],  createdRow:function(row, data, rowIndex)  {  $.each($('td', row), function(colIndex){  if(colIndex == 1)  {  $(this).attr('data-name', 'CustomerName');  $(this).attr('class', 'tablerRow');  $(this).attr('data-type', 'text');  $(this).attr('data-pk', data[0]);  }  if(colIndex == 2)  {  $(this).attr('data-name', 'Gender');  $(this).attr('class', 'tableRow');  $(this).attr('data-type', 'text');  $(this).attr('data-pk', data[0]);  }  if(colIndex == 3)  {  $(this).attr('data-name', 'Address');  $(this).attr('class', 'tableRow');  $(this).attr('data-type', 'text');  $(this).attr('data-pk', data[0]);  }  if(colIndex == 4)  {  $(this).attr('data-name', 'City');  $(this).attr('class', 'tableRow');  $(this).attr('data-type', 'text');  $(this).attr('data-pk', data[0]);  }  if(colIndex == 5)  {  $(this).attr('data-name', 'PostalCode');  $(this).attr('class', 'tableRow');  $(this).attr('data-type', 'text');  $(this).attr('data-pk', data[0]);  }  if(colIndex == 6)  {  $(this).attr('data-name', 'Country');  $(this).attr('class', 'tableRow');  $(this).attr('data-type', 'text');  $(this).attr('data-pk', data[0]);  }  });  }   });  $('#customerName').on( 'keyup', function () {  $('#customerList').DataTable().columns( 1 ).search($('#customerName').val()).draw();  }); });  

The php script which fetches the data from database (testFetch.php) is the following:

 lt;?php   $column = array("CustomerID ","CustomerName","Gender","Address","City","PostalCode","Country");  $query = "SELECT * FROM tbl_customer ";  if(isset($_POST["search"]["value"])) {  $query .= '  WHERE CustomerName LIKE "%'.$_POST["search"]["value"].'%"   OR Gender LIKE "%'.$_POST["search"]["value"].'%"  OR Address LIKE "%'.$_POST["search"]["value"].'%"  OR City LIKE "%'.$_POST["search"]["value"].'%"  OR PostalCode LIKE "%'.$_POST["search"]["value"].'%"  OR Country LIKE "%'.$_POST["search"]["value"].'%"   '; }  if(isset($_POST["order"])) {  $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' '; } else {  $query .= 'ORDER BY CustomerID DESC '; }  $query1 = '';  if($_POST["length"] != -1) {  $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length']; }  $statement = $connect-gt;prepare($query);  $statement-gt;execute();  $number_filter_row = $statement-gt;rowCount();  $result = $connect-gt;query($query . $query1);  $data = array();  foreach($result as $row) {  $sub_array = array();  $sub_array[] = $row['CustomerID'];  $sub_array[] = $row['CustomerName'];  $sub_array[] = $row['Address'];  $sub_array[] = $row['City'];  $sub_array[] = $row['PostalCode'];  $sub_array[] = $row['PostalCode'];  $sub_array[] = $row['Country'];  $data[] = $sub_array; }  function count_all_data($connect) {  $query = "SELECT * FROM tbl_customer";   $statement = $connect-gt;prepare($query);   $statement-gt;execute();   return $statement-gt;rowCount(); }  $output = array(  'draw' =gt; intval($_POST['draw']),  'recordsTotal' =gt; count_all_data($connect),  'recordsFiltered' =gt; $number_filter_row,  'data' =gt; $data );  echo json_encode($output);  ?gt;