【问题标题】:unable $_GET data in PDO using AJAX for product filtering无法在 PDO 中使用 AJAX 进行产品过滤的 $_GET 数据
【发布时间】:2020-01-06 12:48:22
【问题描述】:

无法使用 PDOamd AJAX 过滤产品,

下面的代码使用PDOAJAX 加载数据表单sql,但是当我尝试根据Brand 进行过滤时,它不起作用。尝试调试var_dump 方法,但没有任何帮助。

谁能帮我解决,我如何过滤产品,代码中是否缺少任何东西?

HTML

<div class="md-radio my-1">
     <input type="radio" class="filter_all cate" name="cate" id="<?php echo str_replace(' ', '', $row['sca']); ?>" value="<?php echo $row['sca'] ?>">
     <label for="<?php echo str_replace(' ', '', $row['sca']); ?>">
            <?php echo $row['sca']; ?>
     </label>
</div>

脚本

$(document).ready(function () {
            var flag = 0;
            var fetching = false;
            var done = false;

            function filter_data() {
                // prevent concurrent requests
                if (fetching === true) {
                    return;
                }
                fetching = true;
                var data = {
                    action: 'fetch_data',
                    cate: get_filter('cate'),
                    brand: get_filter('brand'),
                    model: get_filter('model'),
                    sort: get_filter('sort'),
                    date: get_filter('date'),
                    offset: flag,
                    limit: 4
                };
                console.log($.param(data));
                $.ajax({
                    url: "fetch.php?" + $.param(data),
                    type: 'POST'
                })
                        .done(function (data) {
                            console.log('data received');

                            $('.filter_data').append(data); // append

                            // we reached the end, no more data
                            if (data === '<h3>No Data Found</h3>') {
                                done = true;
                            }

                            flag += 4;
                            fetching = false; // allow further requests again
                        })
                        .fail(function (error) {
                            console.log('An error occurred while fetching', error)
                            // TODO: some error handling
                        });
            }

            function get_filter(class_name) {
                var filter = [];
                $('.' + class_name + ':checked').each(function () {
                    filter.push($(this).val());
                });
                return filter;
            }
            $('.filter_all').click(function () {
                filter_data();
            });
            filter_data(); // commented out for debugging purpose
            var $window = $(window);
            var $document = $(document);
            $window.scroll(function () {

                if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 300 && fetching === false && done === false) {
                    console.log('infinite scroll');
                    filter_data();
                }
            });
        });

PHP

<?php

include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/include/function.php");

$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";

if (!empty($_GET['cate'])) {
    $query .= " AND sca IN (" . str_repeat("?,", count($_GET['cate']) - 1) . "?)";
} else {
    $_GET['cate'] = []; // in case it is not set 
}

if (!empty($_GET['brand'])) {
    $query .= " AND product_brand IN (" . str_repeat("?,", count($_GET['brand']) - 1) . "?)";
} else {
    $_GET['brand'] = []; // in case it is not set 
}

if (!empty($_GET['model'])) {
    $query .= " AND mdl IN (" . str_repeat("?,", count($_GET['model']) - 1) . "?)";
} else {
    $_GET['model'] = []; // in case it is not set 
}

if (empty($_GET['sort']) || $_GET['sort'][0] == "date") {
    $query .= " ORDER BY pdt DESC";
} elseif ($_GET["sort"][0] == "ASC" || $_GET["sort"][0] == "DESC") {
    $query .= " ORDER BY prs " . $_GET['sort'][0];
}

if (isset($_GET['limit'])) {

    if (!empty($_GET['offset'])) {
        $query .= " LIMIT " . $_GET['limit'] . " OFFSET " . $_GET['offset'];
    } else {
        $query .= " LIMIT " . $_GET['limit'];
    }
}
$stmt = $conn->prepare($query);
$params = array_merge($_GET['cate'], $_GET['brand'], $_GET['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
    foreach ($result as $row) {
        $parameter = $row['pid'];
        $hashed = md5($salt . $parameter);
        $output .= '<a href="/single_view.php?p=' . $row['id'] . '" class="w-xl-20 w-lg-20 col-md-3 col-6 p-1 p-lg-2">
                            <div class="card border-0 small">
                                <img class="card-img-top rounded-0" src="/upload/thumb/' . $row["im1"] . '" alt="Card image cap">
                                <div class="card-body pb-0 pt-2 px-0">
                                    <h6 class="card-title text-dark text-truncate">' . ucfirst(strtolower($row['tit'])) . '</h6>
                                    <h6 class="card-subtitle mb-1 text-muted text-truncate small">' . $row['product_brand'] . '&nbsp;/&nbsp;' . $row['mdl'] . '</h6>
                                    <p class="card-text"><strong class="card-text text-dark text-truncate">&#x20B9;&nbsp;' . $row['prs'] . '</strong></p>' . timeAgo($row['pdt']) . '
                                </div>
                            </div>
                        </a>';
    }
} else {
    $output = '<h3>No Data Found</h3>';
}
echo $output;
?>

【问题讨论】:

  • 您使用的是type: 'POST',所以$_GET 中不会有任何内容,请改用$_POSTvar_dump($_POST); 在 PHP 的顶部,以确保您正确发送。
  • @JayBlanchard 但我可以获得offsetlimit
  • console.log($.param(data)); 返回什么?查询字符串的构造是否正确?
  • @JayBlanchard in console 我可以看到查询,但查询中未传递所选值
  • 您的所有表单元素是否都具有正确的名称属性或正确的类属性?

标签: php jquery filter


【解决方案1】:

尽管将 ajax 调用定义为帖子,但您仍通过 GET 查询参数发送数据。这是一个安全风险。尝试将您的 AJAX 调用更改为类似的内容,并将您的 $_GET 东西替换为 $_POST

            $.ajax({
                url: '/your-form-processing-page-url-here',
                type: 'POST',
                data: data,
                mimeType: 'multipart/form-data',
                success: function(data, status, jqXHR){
                    alert('Hooray! All is well.');
                    console.log(data);
                    console.log(status);
                    console.log(jqXHR);

                },
                error: function(jqXHR,status,error){
                    // Hopefully we should never reach here
                    console.log(jqXHR);
                    console.log(status);
                    console.log(error);
                }
            });

【讨论】:

  • 试过这是我在var_dump($_POST); array(3) { ["action"]=&gt; string(10) "fetch_data" ["offset"]=&gt; string(1) "0" ["limit"]=&gt; string(1) "4" } 无法在var_dump 中找到所选值
  • console.log(data);在您发送之前并仔细检查您发送的值
猜你喜欢
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 1970-01-01
相关资源
最近更新 更多