There is a code:

$(document).ready(function(){ load_data(); load_data2(); function load_data(query) { $.ajax({ url:"add.php", method:"POST", data:{query:query}, success:function(data) { $('#result').html(data); } }); } function load_data2(query2) { $.ajax({ url:"add2.php", method:"POST", data:{query2:query2}, success:function(data) { $('#result').html(data); } }); } $('#search').keyup(function(){ var search = $(this).val(); if(search != '') { load_data(search); } else { load_data(); } }); $('#search2').keyup(function(){ var search2 = $(this).val(); if(search2 != '') { load_data2(search2); } else { load_data2(); } }); }); 

I have about 15 such checks. How can this all be combined, more precisely, simplified?

enter image description here

enter image description here

  • why do you need 2 server handlers? - Max By
  • I have 15 of them. Initially I connected datatables to search by table columns, as a result, the table is large, 15 columns for 1500 lines, loads the page for a long time and refreshes the page, I decided to do it via ajax. Loads at times faster, and the search does not freeze, just a lot of code. He is somehow, logically, can be combined, perhaps? Server handlers are simply attached to each input; the search is on a specific column in the table. How to implement easier or otherwise I do not know. - scanread
  • I mean, why do you need more than one server search handler? - Maxim By
  • More than one, because I do not know how to combine. For the #search input, I use the search on the first column, for the # search2 input, on the second, for the # search15 input, the search on the last. Under each input I do my sample with a database if (isset ($ _ POST ["query"])) {$ search = mysqli_real_escape_string ($ con, $ _POST ["query"]); $ query = "SELECT * FROM users WHERE fam LIKE '%". $ search. "%'";} else {$ query = "SELECT * FROM users"; } is for the first #search, for the second there is a second query similar, but with a sample from another DB column. How can I simplify - I don't know yet, that's why I ask - scanread
  • There is a picture, how should it be? - Max By

2 answers 2

 <input class="search" data-column="col1" /> <input class="search" data-column="col2" /> $('.search').keyup(function(){ load_data($(this).val(), $(this).data("column")); }); function load_data(searchTerm, columnName) { $.ajax({ url:"add.php", method:"POST", data: { query: searchTerm, column: columnName }, success:function(data) { $('#result').html(data); } }); } 

    Igor's previous answer partially reveals the solution.
    In general, something like this:

     <!-- HTML --> <table> <thead> <tr> <!-- Поисковые поля располагать в шапке таблицы, использовать placeholder --> <th>ID</th> <th><input type="text" class="js-search" data-column="fam" placeholder="Фамилия"></th> <th><input type="text" class="js-search" data-column="im" placeholder="Имя"></th> <th><input type="text" class="js-search" data-column="age" placeholder="Возраст"></th> <th><!-- Остальные поля по шаблону выше --></th> </tr> </thead> <tbody id="result"></tbody> </table> 

    In the client handler, use the closure to store the search state. Ideally, you should use the debounce function to prevent ajax requests from flying every time you press a button.

     // инициализация поиска при готовности разметки $(document).ready(initSearch) function initSearch(){ var fields = {} var $searchFields = $('.js-search') var $result = $('#result') // В обработчике используем функцию задержки обработки события $('.js-search').on('keypress', debounce(function(e){ var $th = $(this) // поле, по которому ищем fields[$th.data('column')] = $th.val() // но на сервер отправляем все заполненные поля $.ajax({ method: 'POST', url: '/search.php', data: fields }).done(function(res){ // в результат вставляем отрендеренный html таблицы $result.html(renderTableResult(res)) }).fail(function(err){ console.log(err) }) },200)) /** * функция формирует разметку результатов поиска * использует не конкатенацию строк, а join массива * @param <array> items - найденные элементы * @return string */ function renderTableResult(items){ // в colspan ставишь количество столбцов if(!items.length) return '<tr><td colspan="3">Не найдено</td></tr>' var html = [] for(var i=0; i < items.length; i++){ html.push('<tr>') // порядковый номер html.push('<td>'+(i+1)+'</td>') // соответсвующие поля html.push('<td>'+ items[i].fam +'</td>') html.push('<td>'+ items[i].im +'</td>') html.push('<td>'+ items[i].age +'</td>') html.push('</tr>') } return html.join('') } } /** * можно и плагин подключить * ВНИМАНИЕ! синтаксис ES2015 * инфо http://jquery.page2page.ru/index.php5/Throttle-debounce * данная функция взята с https://learn.javascript.ru/task/debounce */ function debounce(f, ms) { let timer = null; return function (...args) { const onComplete = () => { f.apply(this, args); timer = null; } if (timer) { clearTimeout(timer); } timer = setTimeout(onComplete, ms); }; } 

    The initial unfiltered data with pagination is up to you to decide how to insert - directly into the markup when the page loads, or a separate ajax request during initialization

    You will receive an object with all the filled fields on the server. It remains only to write a server handler with filtering logic