无法在使用AJAX进行产品筛选时通过PDO获取$_GET数据。

huangapple go评论113阅读模式
英文:

unable $_GET data in PDO using AJAX for product filtering

问题

无法使用PDOAJAX过滤产品,

下面的代码使用PDOAJAXsql加载数据,但是当我尝试根据品牌进行过滤时,它不起作用。尝试调试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>

SCRIPT

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

    function filter_data() {
        // 防止并发请求
        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); // 追加数据

            // 我们到达了末尾,没有更多数据
            if (data === '<h3>No Data Found</h3>') {
                done = true;
            }

            flag += 4;
            fetching = false; // 再次允许请求
        })
        .fail(function (error) {
            console.log('An error occurred while fetching', error)
            // TODO: 处理错误
        });
    }

    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(); // 为了调试目的而注释掉
    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'] = []; // 如果未设置
}

if (!empty($_GET['brand'])) {
    $query .= " AND product_brand IN (" . str_repeat("?,", count($_GET['brand']) - 1) . "?)";
} else {
    $_GET['brand'] = []; // 如果未设置
}

if (!empty($_GET['model'])) {
    $query .= " AND mdl IN (" . str_repeat("?,", count($_GET['model']) - 1) . "?)";
} else {
    $_GET['model'] = []; // 如果未设置
}

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;
?>

请注意,这是您提供的代码的翻译部分,不包括代码中的注释或其他内容。如果需要更多帮助或解释,请随时提问。

英文:

Unable to filter product using PDOamd AJAX,

Below code loads data form sql using PDO and AJAX but when i try to filter based on Brand it doesn't work. tried debug var_dump method but nothing helps.

Can someone help me to solve, how do i filter product, is there anything missing in code?

HTML

&lt;div class=&quot;md-radio my-1&quot;&gt;
&lt;input type=&quot;radio&quot; class=&quot;filter_all cate&quot; name=&quot;cate&quot; id=&quot;&lt;?php echo str_replace(&#39; &#39;, &#39;&#39;, $row[&#39;sca&#39;]); ?&gt;&quot; value=&quot;&lt;?php echo $row[&#39;sca&#39;] ?&gt;&quot;&gt;
&lt;label for=&quot;&lt;?php echo str_replace(&#39; &#39;, &#39;&#39;, $row[&#39;sca&#39;]); ?&gt;&quot;&gt;
&lt;?php echo $row[&#39;sca&#39;]; ?&gt;
&lt;/label&gt;
&lt;/div&gt;

SCRIPT

$(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: &#39;fetch_data&#39;,
cate: get_filter(&#39;cate&#39;),
brand: get_filter(&#39;brand&#39;),
model: get_filter(&#39;model&#39;),
sort: get_filter(&#39;sort&#39;),
date: get_filter(&#39;date&#39;),
offset: flag,
limit: 4
};
console.log($.param(data));
$.ajax({
url: &quot;fetch.php?&quot; + $.param(data),
type: &#39;POST&#39;
})
.done(function (data) {
console.log(&#39;data received&#39;);
$(&#39;.filter_data&#39;).append(data); // append
// we reached the end, no more data
if (data === &#39;&lt;h3&gt;No Data Found&lt;/h3&gt;&#39;) {
done = true;
}
flag += 4;
fetching = false; // allow further requests again
})
.fail(function (error) {
console.log(&#39;An error occurred while fetching&#39;, error)
// TODO: some error handling
});
}
function get_filter(class_name) {
var filter = [];
$(&#39;.&#39; + class_name + &#39;:checked&#39;).each(function () {
filter.push($(this).val());
});
return filter;
}
$(&#39;.filter_all&#39;).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) &gt;= document.body.offsetHeight - 300 &amp;&amp; fetching === false &amp;&amp; done === false) {
console.log(&#39;infinite scroll&#39;);
filter_data();
}
});
});

PHP

&lt;?php
include(&quot;$_SERVER[DOCUMENT_ROOT]/include/config.php&quot;);
include(&quot;$_SERVER[DOCUMENT_ROOT]/include/function.php&quot;);
$query = &quot;SELECT * FROM allpostdata WHERE sts = &#39;1&#39; AND mca=&#39;Vehicle&#39;&quot;;
if (!empty($_GET[&#39;cate&#39;])) {
$query .= &quot; AND sca IN (&quot; . str_repeat(&quot;?,&quot;, count($_GET[&#39;cate&#39;]) - 1) . &quot;?)&quot;;
} else {
$_GET[&#39;cate&#39;] = []; // in case it is not set 
}
if (!empty($_GET[&#39;brand&#39;])) {
$query .= &quot; AND product_brand IN (&quot; . str_repeat(&quot;?,&quot;, count($_GET[&#39;brand&#39;]) - 1) . &quot;?)&quot;;
} else {
$_GET[&#39;brand&#39;] = []; // in case it is not set 
}
if (!empty($_GET[&#39;model&#39;])) {
$query .= &quot; AND mdl IN (&quot; . str_repeat(&quot;?,&quot;, count($_GET[&#39;model&#39;]) - 1) . &quot;?)&quot;;
} else {
$_GET[&#39;model&#39;] = []; // in case it is not set 
}
if (empty($_GET[&#39;sort&#39;]) || $_GET[&#39;sort&#39;][0] == &quot;date&quot;) {
$query .= &quot; ORDER BY pdt DESC&quot;;
} elseif ($_GET[&quot;sort&quot;][0] == &quot;ASC&quot; || $_GET[&quot;sort&quot;][0] == &quot;DESC&quot;) {
$query .= &quot; ORDER BY prs &quot; . $_GET[&#39;sort&#39;][0];
}
if (isset($_GET[&#39;limit&#39;])) {
if (!empty($_GET[&#39;offset&#39;])) {
$query .= &quot; LIMIT &quot; . $_GET[&#39;limit&#39;] . &quot; OFFSET &quot; . $_GET[&#39;offset&#39;];
} else {
$query .= &quot; LIMIT &quot; . $_GET[&#39;limit&#39;];
}
}
$stmt = $conn-&gt;prepare($query);
$params = array_merge($_GET[&#39;cate&#39;], $_GET[&#39;brand&#39;], $_GET[&#39;model&#39;]);
$stmt-&gt;execute($params);
$result = $stmt-&gt;fetchAll();
$total_row = $stmt-&gt;rowCount();
$output = &#39;&#39;;
if ($total_row &gt; 0) {
foreach ($result as $row) {
$parameter = $row[&#39;pid&#39;];
$hashed = md5($salt . $parameter);
$output .= &#39;&lt;a href=&quot;/single_view.php?p=&#39; . $row[&#39;id&#39;] . &#39;&quot; class=&quot;w-xl-20 w-lg-20 col-md-3 col-6 p-1 p-lg-2&quot;&gt;
&lt;div class=&quot;card border-0 small&quot;&gt;
&lt;img class=&quot;card-img-top rounded-0&quot; src=&quot;/upload/thumb/&#39; . $row[&quot;im1&quot;] . &#39;&quot; alt=&quot;Card image cap&quot;&gt;
&lt;div class=&quot;card-body pb-0 pt-2 px-0&quot;&gt;
&lt;h6 class=&quot;card-title text-dark text-truncate&quot;&gt;&#39; . ucfirst(strtolower($row[&#39;tit&#39;])) . &#39;&lt;/h6&gt;
&lt;h6 class=&quot;card-subtitle mb-1 text-muted text-truncate small&quot;&gt;&#39; . $row[&#39;product_brand&#39;] . &#39;&amp;nbsp;/&amp;nbsp;&#39; . $row[&#39;mdl&#39;] . &#39;&lt;/h6&gt;
&lt;p class=&quot;card-text&quot;&gt;&lt;strong class=&quot;card-text text-dark text-truncate&quot;&gt;&amp;#x20B9;&amp;nbsp;&#39; . $row[&#39;prs&#39;] . &#39;&lt;/strong&gt;&lt;/p&gt;&#39; . timeAgo($row[&#39;pdt&#39;]) . &#39;
&lt;/div&gt;
&lt;/div&gt;
&lt;/a&gt;&#39;;
}
} else {
$output = &#39;&lt;h3&gt;No Data Found&lt;/h3&gt;&#39;;
}
echo $output;
?&gt;

答案1

得分: 0

你尽管将数据通过GET查询参数发送,尽管已将ajax调用定义为POST方式。这是一个安全风险。尝试将您的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('好消息!一切正常。');
        console.log(data);
        console.log(status);
        console.log(jqXHR);
    },
    error: function(jqXHR, status, error){
        // 希望我们永远不会到达这里
        console.log(jqXHR);
        console.log(status);
        console.log(error);
    }
});
英文:

You are sending data via GET query parameters despite defining the ajax call as a post. That's a security risk. Try changing your AJAX call to something like this, and replace youyr $_GET stuff to $_POST.

            $.ajax({
url: &#39;/your-form-processing-page-url-here&#39;,
type: &#39;POST&#39;,
data: data,
mimeType: &#39;multipart/form-data&#39;,
success: function(data, status, jqXHR){
alert(&#39;Hooray! All is well.&#39;);
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);
}
});

huangapple
  • 本文由 发表于 2020年1月6日 20:48:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定