Как связать пагинацию с фильтрацией продуктов. Фильтр продуктов сделать на ajax?
Код JS
$(document).ready(function () { filter_data(); function filter_data() { $('.catalog__grid').html('<div id="loading" style="" ></div>'); const action = 'list-products'; const minimum_price = $('#input-0').val(); const maximum_price = $('#input-1').val(); const brand = get_filter('brand'); const cpu_series = get_filter('cpu_series'); const graphics = get_filter('graphics'); const graphics_type = get_filter('graphics_type'); const ram = get_filter('ram'); const hdd = get_filter('hdd'); const ssd = get_filter('ssd'); const os = get_filter('os'); $.ajax({ url: '../data/list-products.php', method: 'POST', data: { action: action, brand: brand, cpu_series: cpu_series, graphics: graphics, graphics_type: graphics_type, ram: ram, hdd: hdd, ssd: ssd, os: os, minimum_price: minimum_price, maximum_price: maximum_price, }, success: function (data) { $('.catalog__grid').html(data); makePagination(); setImageOnHover('mouseover'); setImageOnHover('mouseout'); }, }); } function get_filter(class_name) { var filter = []; $('.' + class_name + ':checked').each(function () { filter.push($(this).val()); }); return filter; } $('.custom-checkbox__field').click(function () { filter_data(); }); rangeSlider.noUiSlider.on('update', (values, handle) => { inputs[handle].value = Math.round(values[handle]); filter_data(); }); document.querySelector('.catalog__reset-btn').onclick = function () { var brand_elements = document.getElementsByClassName('custom-checkbox__field'); for (var count = 0; count < brand_elements.length; count++) { brand_elements[count].checked = false; } filter_data(); }; }); |
$(document).ready(function () { filter_data(); function filter_data() { $('.catalog__grid').html('<div id="loading" style="" ></div>'); const action = 'list-products'; const minimum_price = $('#input-0').val(); const maximum_price = $('#input-1').val(); const brand = get_filter('brand'); const cpu_series = get_filter('cpu_series'); const graphics = get_filter('graphics'); const graphics_type = get_filter('graphics_type'); const ram = get_filter('ram'); const hdd = get_filter('hdd'); const ssd = get_filter('ssd'); const os = get_filter('os'); $.ajax({ url: '../data/list-products.php', method: 'POST', data: { action: action, brand: brand, cpu_series: cpu_series, graphics: graphics, graphics_type: graphics_type, ram: ram, hdd: hdd, ssd: ssd, os: os, minimum_price: minimum_price, maximum_price: maximum_price, }, success: function (data) { $('.catalog__grid').html(data); makePagination(); setImageOnHover('mouseover'); setImageOnHover('mouseout'); }, }); } function get_filter(class_name) { var filter = []; $('.' + class_name + ':checked').each(function () { filter.push($(this).val()); }); return filter; } $('.custom-checkbox__field').click(function () { filter_data(); }); rangeSlider.noUiSlider.on('update', (values, handle) => { inputs[handle].value = Math.round(values[handle]); filter_data(); }); document.querySelector('.catalog__reset-btn').onclick = function () { var brand_elements = document.getElementsByClassName('custom-checkbox__field'); for (var count = 0; count < brand_elements.length; count++) { brand_elements[count].checked = false; } filter_data(); }; });
Код PHP
<?php include ('connect.php'); $limit = 4; if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page = 1; }; $start_from = ($page - 1) * $limit; if (isset($_POST["action"])) { $query = " SELECT * FROM pc WHERE product_status = '1' "; if (isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"])) { $query.= " AND price BETWEEN '" . $_POST["minimum_price"] . "' AND '" . $_POST["maximum_price"] . "' 'AND LIMIT 1' "; } if (isset($_POST["brand"])) { $brand_filter = implode("','", $_POST["brand"]); $query.= " AND brand IN('" . $brand_filter . "') "; } if (isset($_POST["cpu_series"])) { $ram_filter = implode("','", $_POST["cpu_series"]); $query.= " AND cpu_series IN('" . $ram_filter . "') "; } if (isset($_POST["graphics"])) { $graphics_filter = implode("','", $_POST["graphics"]); $query.= " AND graphics IN('" . $graphics_filter . "') "; } if (isset($_POST["graphics_type"])) { $graphics_type_filter = implode("','", $_POST["graphics_type"]); $query.= " AND graphics_type IN('" . $graphics_type_filter . "') "; } if (isset($_POST["ram"])) { $ram_filter = implode("','", $_POST["ram"]); $query.= " AND ram IN('" . $ram_filter . "') "; } if (isset($_POST["hdd"])) { $hdd_filter = implode("','", $_POST["hdd"]); $query.= " AND hdd IN('" . $hdd_filter . "') "; } if (isset($_POST["ssd"])) { $ssd_filter = implode("','", $_POST["ssd"]); $query.= " AND ssd IN('" . $ssd_filter . "') "; } if (isset($_POST["os"])) { $os_filter = implode("','", $_POST["os"]); $query.= " AND os IN('" . $os_filter . "') "; } $result = mysqli_query($conn, $query . ' LIMIT ' . $start_from . ', ' . $limit . ''); $result_row = mysqli_fetch_all($result); $total_row = mysqli_num_rows($result); $output = ''; if ($total_row > 0) { foreach ($result_row as $row) { $arr = explode(',', $row[12]); = < divclass = "catalog__product product" > < divclass = "product__box" > < divclass = "product__image" > < aclass = "product__image-link"href = "#" > < pictureclass = "product__image-picture" > < ? php ?> <source srcset="<?=$arr[0] ?>.jpg"> <img class="product__image-main" src="<?=$arr[0] ?>.jpg" alt="<?=$row[13] ?>"></img> <?php ?> </picture> <div class="product__image-hover"> <?php foreach ($arr as $img) { ?> <div class="product__image-hover-part" data-src="<?=$img ?>.jpg"></div> <?php } ?> </div> <ul class="product__image-pagination image-pagination" aria-hidden="true"></ul> </a> </div> <div class="product__header"> <a href="#"> <h3 class="product__title"><?=$row[2] ?></h3> </a> </div> </div> </div> } } else { $output = '<h3>No Data Found</h3>'; } echo $output; } $result_count = mysqli_query($conn, "SELECT COUNT(*) As total_data FROM `pc`"); $total_records = mysqli_fetch_array($result_count); $total_data = $total_records['total_data']; $total_pages = ceil($total_data / $limit); $pagination = ''; $pagination .= " <div class='pagination'> "; if ($page > 1) { $prev = $page - 1; $pagination .= " <a class='pagination__btn' href='?page=" . $prev . "'>Предыдущая</a> "; } $pagination .= " <ul class='pagination__list'> "; for ($i = 1; $i <= $total_pages; $i++) { $active_class = ''; if ($i == $page) { $active_class = 'pagination__list-link--active'; } $pagination .= "<li class='pagination__list-item'><a class='pagination__list-link " . $active_class . " ' href='?page=" . $i . "'>" . $i . "</a></li>"; } $pagination .= " </ul> "; if ($page < $total_pages) { $pagination .= "<a class='pagination__btn' href='?page=" . ($page + 1) . "'>Следующая</a> "; } $pagination .= " </div> "; echo $pagination; |
<?php include ('connect.php'); $limit = 4; if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page = 1; }; $start_from = ($page - 1) * $limit; if (isset($_POST["action"])) { $query = " SELECT * FROM pc WHERE product_status = '1' "; if (isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"])) { $query.= " AND price BETWEEN '" . $_POST["minimum_price"] . "' AND '" . $_POST["maximum_price"] . "' 'AND LIMIT 1' "; } if (isset($_POST["brand"])) { $brand_filter = implode("','", $_POST["brand"]); $query.= " AND brand IN('" . $brand_filter . "') "; } if (isset($_POST["cpu_series"])) { $ram_filter = implode("','", $_POST["cpu_series"]); $query.= " AND cpu_series IN('" . $ram_filter . "') "; } if (isset($_POST["graphics"])) { $graphics_filter = implode("','", $_POST["graphics"]); $query.= " AND graphics IN('" . $graphics_filter . "') "; } if (isset($_POST["graphics_type"])) { $graphics_type_filter = implode("','", $_POST["graphics_type"]); $query.= " AND graphics_type IN('" . $graphics_type_filter . "') "; } if (isset($_POST["ram"])) { $ram_filter = implode("','", $_POST["ram"]); $query.= " AND ram IN('" . $ram_filter . "') "; } if (isset($_POST["hdd"])) { $hdd_filter = implode("','", $_POST["hdd"]); $query.= " AND hdd IN('" . $hdd_filter . "') "; } if (isset($_POST["ssd"])) { $ssd_filter = implode("','", $_POST["ssd"]); $query.= " AND ssd IN('" . $ssd_filter . "') "; } if (isset($_POST["os"])) { $os_filter = implode("','", $_POST["os"]); $query.= " AND os IN('" . $os_filter . "') "; } $result = mysqli_query($conn, $query . ' LIMIT ' . $start_from . ', ' . $limit . ''); $result_row = mysqli_fetch_all($result); $total_row = mysqli_num_rows($result); $output = ''; if ($total_row > 0) { foreach ($result_row as $row) { $arr = explode(',', $row[12]); = < divclass = "catalog__product product" > < divclass = "product__box" > < divclass = "product__image" > < aclass = "product__image-link"href = "#" > < pictureclass = "product__image-picture" > < ? php ?> <source srcset="<?=$arr[0] ?>.jpg"> <img class="product__image-main" src="<?=$arr[0] ?>.jpg" alt="<?=$row[13] ?>"></img> <?php ?> </picture> <div class="product__image-hover"> <?php foreach ($arr as $img) { ?> <div class="product__image-hover-part" data-src="<?=$img ?>.jpg"></div> <?php } ?> </div> <ul class="product__image-pagination image-pagination" aria-hidden="true"></ul> </a> </div> <div class="product__header"> <a href="#"> <h3 class="product__title"><?=$row[2] ?></h3> </a> </div> </div> </div> } } else { $output = '<h3>No Data Found</h3>'; } echo $output; } $result_count = mysqli_query($conn, "SELECT COUNT(*) As total_data FROM `pc`"); $total_records = mysqli_fetch_array($result_count); $total_data = $total_records['total_data']; $total_pages = ceil($total_data / $limit); $pagination = ''; $pagination .= " <div class='pagination'> "; if ($page > 1) { $prev = $page - 1; $pagination .= " <a class='pagination__btn' href='?page=" . $prev . "'>Предыдущая</a> "; } $pagination .= " <ul class='pagination__list'> "; for ($i = 1; $i <= $total_pages; $i++) { $active_class = ''; if ($i == $page) { $active_class = 'pagination__list-link--active'; } $pagination .= "<li class='pagination__list-item'><a class='pagination__list-link " . $active_class . " ' href='?page=" . $i . "'>" . $i . "</a></li>"; } $pagination .= " </ul> "; if ($page < $total_pages) { $pagination .= "<a class='pagination__btn' href='?page=" . ($page + 1) . "'>Следующая</a> "; } $pagination .= " </div> "; echo $pagination;
Дополнительно:
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос
Для связывания пагинации с фильтрацией продуктов и реализации фильтрации продуктов через AJAX, вам потребуется использовать следующий подход:
1. Создайте HTML форму с фильтрами продуктов, которая будет отправлять AJAX запросы для получения отфильтрованных результатов.
2. На стороне сервера (например, на PHP) создайте скрипт, который будет обрабатывать AJAX запросы и возвращать отфильтрованные результаты. Для этого вам нужно будет использовать SQL запросы для выборки данных с учетом переданных фильтров.
3. На стороне клиента (JS) напишите скрипт, который будет отправлять AJAX запросы при изменении значений фильтров и обновлять содержимое страницы с результатами.
4. Для связывания пагинации с фильтрацией продуктов, вы можете передавать параметры страницы в AJAX запросе и обрабатывать их на сервере для выборки соответствующих результатов.
Пример PHP скрипта для обработки AJAX запроса и возврата отфильтрованных результатов:
if(isset($_POST['filter'])) { $filter = $_POST['filter']; $page = $_POST['page']; // Здесь выполняется SQL запрос с учетом переданных фильтров и страницы $query = "SELECT * FROM products WHERE category = '$filter' LIMIT $page, 10"; // Выполнение запроса и формирование HTML для результатов $results = mysqli_query($connection, $query); while($row = mysqli_fetch_array($results)) { echo '<div>' . $row['name'] . '</div>'; } }
Пример JS скрипта для отправки AJAX запроса при изменении фильтров и обновления результатов:
$('#filterForm').on('change', function() { var filter = $(this).serialize(); var page = 1; $.ajax({ url: 'filter.php', type: 'POST', data: {filter: filter, page: page}, success: function(response) { $('#results').html(response); } }); });
Таким образом, вы сможете связать пагинацию с фильтрацией продуктов и реализовать фильтрацию через AJAX на вашем сайте.