javascript - 如何使用 PHP、AJAX 和 JS 的复选框来过滤类似产品?

标签 javascript php jquery mysql ajax

这是我想要实现的目标的图像 - enter image description here

我的数据库表示例 - enter image description here

我的目标是在不刷新页面的情况下获得与当前显示的产品类似的产品。我试图通过使用复选框来查找类似的产品。

我首先使用 $_GET['id'] 获取 id,它应该等于我表中的值之一。

然后,我使用 PDO Fetch 获取该特定 ID 的产品名称、品牌、数量和价格,并将其存储为字符串。

我需要帮助的是使用 JQuery/AJAX 获取选中的复选框,然后将信息发送到 PHP 文件,该文件将检查过滤器结果是否与表中的任何数据匹配。

我该怎么做?

这是我的product.php 文件

 <?php
    require ('includes/db.php');

    $id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12

    $stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
    $result = $stmt->execute(array());
    $products   = $stmt->fetch(PDO::FETCH_ASSOC);

    $prod_name = $products['prod_name']; //Product Name

    $brand = $products['brand']; //Product Brand
    $quantity = $products['quantity']; //Product Quantity
    $calories = $products['calories'];  //Product Calories
    $price = $products['price'];    //Product Price


?>

    <!DOCTYPE html>
     <html>
    <head>
        <title><?php echo "$brand $prod_name"; ?></title>
    </head>

    <body>
        <h1><?php echo $prod_name; ?></h1>
        <br />

        <p>Brand = <?php echo " $brand"; ?></p>
        <p>Quantity = <?php echo " $quantity"; ?></p>
        <p>Calories = <?php echo " $calories"; ?></p>
        <p>Price = <?php echo " $price"; ?></p>

        <br />

        <p style="text-align: center;">Find Similar Products</p>

        <form> 
        <div class="checkboxes">
            <label>
                <input name="brand" type="checkbox" value="<?php echo $brand; ?>">
                <span>Brand</span> <!--Brand Checkbox-->
            </label>
        </div>
        <div class="checkboxes">
            <label>
                <input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
                <span>Quantity</span> <!--Quantity Checkbox-->
            </label>
        </div>
        <div class="checkboxes">
            <label>
                <input name="calories" type="checkbox" value="<?php echo $calories; ?>">
                <span>Calories</span> <!--Calories Checkbox-->
            </label>
        </div>
        <div class="checkboxes">
            <label>
                <input name="price" type="checkbox" value="<?php echo $price; ?>">
                <span>Price</span>  <!--Price Checkbox-->
            </label>
        </div>
    </form>

    </body>
</html>

最佳答案

我设法解决了这个问题,很高兴我没有放弃。

我的product.php文件

<?php
require ('/db.php');

$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12

$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products   = $stmt->fetch(PDO::FETCH_ASSOC);

$prod_name = $products['prod_name']; //Product Name

$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories'];  //Product Calories
$price = $products['price'];    //Product Price


?>

<!DOCTYPE html>
 <html>
<head>
    <title><?php echo "$brand $prod_name"; ?></title>
</head>

<body>
    <h1><?php echo $prod_name; ?></h1>
    <br />

    <p>Brand = <?php echo " $brand"; ?></p>
    <p>Quantity = <?php echo " $quantity"; ?></p>
    <p>Calories = <?php echo " $calories"; ?></p>
    <p>Price = <?php echo " $price"; ?></p>

    <br />

    <p style="text-align: center;">Find Similar Products</p>

    <form method="post" action=""> 
    <div class="checkboxes">
        <label>
            <input name="brand" type="checkbox" value="<?php echo $brand; ?>">
            <span>Brand</span> <!--Brand Checkbox-->
        </label>
    </div>
    <div class="checkboxes">
        <label>
            <input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
            <span>Quantity</span> <!--Quantity Checkbox-->
        </label>
    </div>
    <div class="checkboxes">
        <label>
            <input name="calories" type="checkbox" value="<?php echo $calories; ?>">
            <span>Calories</span> <!--Calories Checkbox-->
        </label>
    </div>
    <div class="checkboxes">
        <label>
            <input name="price" type="checkbox" value="<?php echo $price; ?>">
            <span>Price</span>  <!--Price Checkbox-->
        </label>
    </div>
</form>
<div class="filter_container">

    <div style="clear:both;"></div>
</div>
<script type="text/javascript" src="/js/filter.js"></script>

<input name="prod_name" value="<?php echo $prod_name ?>" style="display:none;"/>
<!--Hidden product name-->
</body>
</html>

这是我的 JS 文件

$(document).ready(function() {
function showValues() {


    var brand;  
    var quantity;   
    var calories;       
    var price;      

    //Gets product name
    var prod_name = $('input[name="prod_name"]').val(); 

    //Gets brand
    if($('input[name="brand"]').is(':checked')) 
        {brand = $('input[name="brand"]').val();} else {brand = ""}

    //Gets quantity
    if($('input[name="quantity"]').is(':checked')) 
        {quantity = $('input[name="quantity"]').val();} else {quantity = ""}

    //Gets calories
    if($('input[name="calories"]').is(':checked')) 
        {calories = $('input[name="calories"]').val();} else {calories = ""}

    //Gets price
    if($('input[name="price"]').is(':checked'))  
        {price = $('input[name="price"]').val();} else {price = ""}


        $.ajax({
        type: "POST",
        url: "/query.php",
        data: {'brand':brand, 'quantity':quantity, 'calories':calories, 'prod_name':prod_name}, 
        cache: false,
        success: function(data){
            $('.filter_container').html(data)
                }
            });


}

//Call function when checkbox is clicked
$("input[type='checkbox']").on( "click", showValues );

//Remove checked when checkbox is checked
$(".checkboxes").click(function(){
    $(this).removeAttr('checked');      
    showValues();
});
});

这是我的 PHP 文件

<?php
include('/db.php');

$prod_name = $_POST['prod_name'];

$Cbrand = $_POST['brand'];
$Cquantity = $_POST['quantity'];
$Ccalories = $_POST['calories'];
$Cprice = $_POST['price'];


if(!empty($Cbrand))
{
    $data1 = "brand = '$Cbrand' AND";
}else{
    $data1 = "";
}
if(!empty($Cquantity))
{
    $data2 = "quantity = '$Cquantity' AND";
}else{
    $data2 = "";
}
if(!empty($Ccalories))
{
    $data3 = "calories = '$Ccalories' AND";
}else{
    $data3 = "";
}
if(!empty($Cprice))
{
    $data4 = "price = '$Cprice'";
}else{
    $data4 = "";
}


$main_string = "WHERE $data1 $data2 $data3 $data4"; //All details

$stringAnd = "AND"; //And

$main_string = trim($main_string); //Remove whitespaces from the beginning and end of the main string

$endAnd = substr($main_string, -3); //Gets the AND at the end

if($stringAnd == $endAnd)
{
$main_string = substr($main_string, 0, -3);
}else if($main_string == "WHERE"){
    $main_string = "";
}
else{
    $main_string = "WHERE $data1 $data2 $data3 $data4";
}

if($main_string == ""){ //Doesn't show all the products

}else{

$sql = "SELECT COUNT(*) FROM products $main_string";

if ($res = $handler->query($sql)) {

/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
  $sql = "SELECT * FROM products $main_string";
foreach ($handler->query($sql) as $pro) {

if(($pro['prod_name'] == $prod_name) && ($res->fetchColumn() < 2))
{
    //The product currently being displayed is blank when using the filter
}
else{
    ?>

    <!------------------------------------------------------------------------------------------------------------------------------------------------->    

    <div class="form-result">
        <td><?=strtoupper($pro['brand']) + " " + strtoupper($pro['prod_name']); ?></td>
    </div>

    <!------------------------------------------------------------------------------------------------------------------------------------------------->


    <?php
}
}
}    /* No rows matched -- do something else */
    else {
        ?>
        <div align="center"><h2 style="font-family:'Arial Black', Gadget, sans-serif;font-size:30px;color:#0099FF;">No Results with this filter</h2></div>
        <?php
        }
    }
}
$handler = null;
$res = null;
?>

关于javascript - 如何使用 PHP、AJAX 和 JS 的复选框来过滤类似产品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31627874/

相关文章:

javascript - 当用户向下滚动页面时,导航和下拉菜单之间的空间由于位置 : fixed

javascript - 在脚本中使用 gulp-inline-source 和 ES6 代码

javascript - 服务器和浏览器之间的时间同步

php - 将空值插入日期时间字段

javascript - 为什么这个 "checked"不起作用?

php - 无法使用 Guzzle 请求发送 cookie

php - 删除新闻文件中的重复数据

javascript - JQuery 遍历多个/所有具有特定名称的 HTML 元素

javascript - MMENU jquery 插件将所有 JS 脚本加倍

JQuery Onclick Image 显示隐藏的表格行