我使用 PHP 的 AJAX 分页无法正常工作

问题描述 投票:0回答:1

我正在尝试通过使用 PHP 进行过滤来进行 AJAX 分页,但是分页不起作用,数据根据需要加载到页面上并且过滤也很好但是当点击页面时,没有响应..

带有分页查询的我的 PHP 代码

        if(isset($_POST['category'])) {

    // Filter query
    $query ='';
$seller_filter = isset($_POST['level']) ? $_POST['level'] : '';
$sub_filter = isset($_POST['sub']) ? $_POST['sub'] : '';
$price_filter = isset($_POST['price']) ? $_POST['price'] : '';
$search_filter = isset($_POST['search']) ? $_POST['search'] : '';
$condition = htmlspecialchars(trim(strip_tags(stripslashes(stripcslashes($search_filter)))));
// Default limit
$limit = isset($_POST['per-page']) ? $_POST['per-page'] : 3;

// Default offset
$offset = 0;
$current_page = 1;
if(isset($_POST['page-number'])) {
    $current_page = (int)$_POST['page-number'];
    $offset = ($current_page * $limit) - $limit;
}

    $query .= "SELECT tag_name, room, sellers.seller_id,sellers.image,price,sellers.category_id,sellers.type,sellers.badge,categories.category, 
                COUNT(DISTINCT comments.user_id) AS total, ROUND(AVG(rating),1) AS rate,AVG(odds) AS odda FROM sellers 
                INNER JOIN categories ON sellers.category_id=categories.id 
                LEFT JOIN comments ON sellers.seller_id=comments.seller_id 
                LEFT JOIN posts ON sellers.seller_id=posts.seller_id
                LEFT JOIN keywords ON sellers.seller_id=keywords.seller_id
                WHERE category = :cat";
            if(!empty($seller_filter)){
                $query .=" AND sellers.badge = :bagt ";
            }else 
            if(!empty($sub_filter)){
                $query .=" AND sellers.type = :celt ";
            }else 
            if(!empty($price_filter)){
                $query .=" AND sellers.price BETWEEN $price_filter";
            }else 
            if(!empty($condition)){
                $query .=" AND sellers.room LIKE '%".$condition."%'";
                $query .=" OR tag_name LIKE '%".$condition."%'";
            }else 
            if(!empty($sub_filter) && !empty($seller_filter) && !empty($condition)) {
                $query .=" AND sellers.type = :celt AND sellers.badge = :bagt AND (sellers.room LIKE '%".$condition."%' OR tag_name LIKE '%".$condition."%') ";
            }

        $query .=" GROUP BY sellers.seller_id ";
        $query .=" ORDER BY rate DESC";
        $query .=" LIMIT $limit";

            $statement = $conn->prepare($query);
            $statement->bindParam(':cat',$_POST['category']);
            if(!empty($seller_filter)){
                $statement->bindParam(':bagt',$seller_filter);
            }else 
            if(!empty($sub_filter)){
                $statement->bindParam(':celt',$sub_filter);
            }
            $statement->execute();
            $statement->setFetchMode(PDO::FETCH_ASSOC); //PDO::FETCH_OBJ
            $result = $statement->fetchAll();
            if($result) { 
                foreach($result as $product){

                $paged_products = array_slice($product, $offset, $limit);
                    // Define total products
                    $total_products = count($product);
                    // Get the total pages rounded up the nearest whole number
                    $total_pages = ceil( $total_products / $limit );
                    // Determine whether or not pagination should be made available.
                    $paged = $total_products > count($paged_products) ? true : false;
                    ?>
                    <div class="card col-sm-3 me-1 mt-3 product-wrapper"  style="width:12.7rem;height: 22rem;">
                                <?php echo '<a href=products.php?category='.preg_replace('#[-]+#', '-', trim($product['category'])).'&room='.preg_replace('#[-]+#', '-', trim($product ['room'])).'&seller_id='.preg_replace('#[-]+#', '-', trim($product ['seller_id'])).'>
                        <img src="../seller/' .htmlspecialchars($product ['image']).'" class="img-top  img-fluid bg-light" alt="...">
                        </a>';?> 
                        <div class="card-body">
                            <div class="row border-bottom">
                            <span class="badge rounded-pill bg-primary w-50 position-absolute top-1 start-50 translate-middle">
                                <?php
                            if($product ['badge'] == '0') {
                                echo htmlspecialchars('NEW');
                            } elseif($product ['badge'] == '1') {
                                echo htmlspecialchars('Level 1');
                            } elseif($product ['badge'] == '2') {
                                echo htmlspecialchars('Level 2');
                            } else {
                                echo htmlspecialchars('PRO');
                            }
                ?> seller</span>
                                <h5 class="card-title text-center fw-bolder fs-5 mt-3"><?php echo htmlspecialchars($product ['room']);?></h5>
                                <p class="text-center text-decoration-none text-dark"  style="font-size:1rem;" ><?php echo htmlspecialchars($product ['category']);?></p>
                                <p class="text-danger"><i class="fa-solid fa-star"></i><?php echo htmlspecialchars($product ['rate']);?>
                                    <span class="text-end fw-light text-dark">(<?php echo htmlspecialchars($product ['total']);?>)</span>
                                </p>
                            </div>
                            <p class="card-title text-start fw-bolder text-decoration-none text-dark" style="font-size:0.7rem;">STARTING AT
                            <span class="text-start fw-bolder text-decoration-underline" style="font-size:.8rem;">US &dollar;<?php echo htmlspecialchars($product ['price']);?></span>
                            </p>
                        </div>
                    </div>
            <?php }if ($paged) {
                $query = isset($_POST) ?  'data-query="' . http_build_query($_POST) . '"' : '';
            ?>
            <nav class="col-md-12 mt-3" >
                <ul class="pagination">
                    <li class="page-item <?php echo $current_page === 1 ? 'disabled' : ''; ?>">
                      <a class="page-link" href="#" data-page-number="<?php echo $current_page - 1; ?>" <?php echo $query; ?> >
                        <span>«</span>
                      </a>
                    </li>
                <?php
                for($page_number = 1; $page_number <= $total_pages; $page_number++) { ?>
                    <li class="page-item <?php echo isset($_POST['page-number']) && $_POST['page-number'] == $page_number ? 'active' : ''; ?>"><a class="page-link" href="#" data-page-number="<?php echo $page_number; ?>" <?php echo $query; ?>><?php echo $page_number; ?></a></li>
                <?php } ?>
                    <li class="page-item <?php echo $current_page === (int)$total_pages ? 'disabled' : ''; ?>">
                      <a class="page-link" href="#" data-page-number="<?php echo $current_page + 1; ?>" <?php echo $query; ?>>
                        <span>»</span>
                      </a>
                    </li>
                </ul>
            </nav>
            <?php  }
            }
            else {
                echo '<div class="text-danger display-1">OOPS! NOTHING IS HERE YET!</div>';
            }
    }

AJAX 查询

    $(document).ready(function(){

        load_data();
        function load_data(category='<?php echo $_GET['category'];?>',query='',page_number){
        $.ajax({
            method:"POST",
            url:"producta.php",
            data:{'category':category,'page-number':page_number,'query':query},
            success: function(data){
                $('#all-products').html(data);
            }
        })
    }
    $(document).on('click', '.page-link', function(e){
            e.preventDefault();
            var page_number = $(this).data('page-number');
            var query;
            
            if( $(this).data('query') ) {
                query = '?' + $(this).data('query');
            }
            else {
                query = '';
            }
            
            $.post('producta.php'+query, {'page-number' : page_number,'query' : query}, function(data){
                $('#all-products').html(data);
            })
        })
$(document).on('submit', '#filter-form', function(e){
    e.preventDefault();
    
    var form = $(this);
    
    $.post('producta.php?category=<?php echo $_GET['category'];?>', $(form).serialize(), function(data){
        $('#all-products').html(data);
    })
    
})
});

有人可以帮我指出我在分页方面做错了什么吗?我已经在 stackoverflow 上查看了其他问题,但实际上我无法弄清楚查询中的问题是什么。当我单击页面链接时,页面变为空白。没有数据显示。我认为问题出在我的分页和 Ajax 查询中,但我想不通。我需要第二个头脑来帮忙

php ajax pagination
1个回答
0
投票

检查 PHP 代码的第一行:

if(isset($_POST['category'])) {

但是您的

$.post()
请求中没有传递类别:

$.post('producta.php'+query, {'page-number' : page_number,'query' : query}, function(data){
    $('#all-products').html(data);
})

假设

category
包含在传递给
query
的字符串中,您可以执行以下操作:

parse_str(ltrim($_POST['query'] ?? '', '?'), $queryArray);
$_POST = array_merge($queryArray, $_POST);

无需使用

isset()
测试每个输入,您可以使用 null 合并运算符

$seller_filter = $_POST['level'] ?? '';
$sub_filter = $_POST['sub'] ?? '';
$price_filter = $_POST['price'] ?? '';
$search_filter = $_POST['search'] ?? '';

这条线没有意义,不能替代参数化:

$condition = htmlspecialchars(trim(strip_tags(stripslashes(stripcslashes($search_filter)))));

您仍然将

$price_filter
$condition
直接传递到您的查询中,而不是使用参数。这非常容易被利用,应该得到纠正。

构建查询时,永远无法到达

else if
链的最后一个,因为
!empty($sub_filter)
在链中的第二个条件中已经得到满足。也许这些条件中的每一个都应该是独立的
if
陈述?

您已经计算了

$offset
但没有将其传递到您的查询中:

$offset = ($current_page * $limit) - $limit;

// missing offset
$query .=" LIMIT $limit";

您需要根据过滤条件进行

COUNT
查询,以确定需要什么(如果有)分页。

这段代码和相关代码毫无意义,因为您已经在 SQL 中进行分页:

$paged_products = array_slice($product, $offset, $limit);

在这里使用

htmlspecialchars()
,对于类似的行,没有意义:

echo htmlspecialchars('NEW');

可能还有其他问题,但希望这足以让您朝着正确的方向前进。

© www.soinside.com 2019 - 2024. All rights reserved.