【问题标题】:Get and SUM the value of dynamic and multiple element using jQuery/Javascript使用 jQuery/Javascript 获取并求和动态和多元素的值
【发布时间】:2022-01-09 05:45:50
【问题描述】:

我的购物车中有一份产品清单。现在,我想计算购物车中的所有产品价格。但我仍然不知道如何从动态元素中获取和计算值。这是我的购物车中动态产品的代码:

<div class="modal fixed-right fade" id="modalShoppingCart" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-vertical" role="document">
    <div class="modal-content">
      <ul class="list-group list-group-lg list-group-flush">
        <?php 
          $no = 1;
          $query = mysqli_query($con, "SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price FROM cart AS c LEFT JOIN product AS p ON c.product_id= p.id LEFT JOIN user AS u ON c.user_id=u.id WHERE c.product_id = p.id GROUP BY p.id")or die(mysqli_error($con));

          while($data = mysqli_fetch_array($query)){
            $product_id = $data['product_id'];
            $sql  = mysqli_query($con, "SELECT COUNT(product_id) FROM cart WHERE product_id='$product_id' GROUP BY product_id ");

            $row = mysqli_fetch_array($sql);
            $quantity = $row['COUNT(product_id)'];

            $sale_price = (int)$data['sale_price'] * $quantity;
        ?>
        <li class="list-group-item">
          <div class="row align-items-center">
            <div class="col-4">
              <a href="product.html">
                <img class="img-fluid" src="../assets/img/<?php echo $data['thumbnail']; ?>" alt="...">
              </a>
            </div>
            <div class="col-8">
              <p class="font-size-sm font-weight-bold mb-6">
                <a class="text-body" href="product.php"><?php echo $data['name']; ?></a> <br>
                <span class="text-muted"><?php echo 'Rp'.(str_replace(',', '.', number_format($sale_price))) ?? 'Rp0'; ?></span>
                <input type="hidden" name="sale_price" class="sale_price<?php echo $no++; ?>" value="<?php echo $sale_price; ?>">
              </p>
              <div class="d-flex align-items-center">
                <input type="number" class="d-inline-block form-control form-control-xxs w-auto m-width-65" name="quantity" value="<?php echo $quantity; ?>">
                <a class="font-size-xs text-gray-400 ml-auto" href="hapus-produk-cart.php?id=<?php echo $data['id']; ?>">
                  <i class="fe fe-x"></i> Hapus
                </a>
              </div>
            </div>
          </div>
        </li>
        <?php } ?>
      </ul>

      <div class="modal-footer line-height-fixed font-size-sm bg-light mt-auto">
        <strong>Total</strong> <strong class="ml-auto"></strong>
      </div>

      <div class="modal-body">
        <a class="btn btn-block btn-dark" href="checkout.php">Checkout Pesanan</a>
      </div>
    </div>
  </div>
</div>

由于产品是动态的,我不知道如何获取&lt;input type="hidden" name="sale_price" class="sale_price&lt;?php echo $no++; ?&gt;" value="&lt;?php echo $sale_price; ?&gt;"&gt; 中的值。以及如何使用 jQuery 或 javascript 计算它。你能帮我怎么做吗?我真的需要你们的帮助。提前谢谢你。

【问题讨论】:

    标签: javascript php jquery mysql


    【解决方案1】:

    从哪里开始?我不打算处理使用prepared statements 的需要,但我建议您阅读一些有关 SQL 注入的信息。所以,让我们尝试从您的第一个查询开始 -

    SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price
    FROM cart AS c
    LEFT JOIN product AS p ON c.product_id= p.id
    LEFT JOIN user AS u ON c.user_id=u.id
    WHERE c.product_id = p.id
    GROUP BY p.id
    

    为什么 LEFT 加入?这些应该是 INNER 连接,当然?如果 SELECT 列表中没有返回用户表,为什么还要加入用户表?此当前查询将返回所有购物车及其各自的产品和用户。可能不是你想要的。也许您想要当前用户的购物车和相关产品?我将在此基础上继续。

    SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price, c.quantity * p.sale_price AS line_item_total
    FROM cart AS c
    JOIN product AS p ON c.product_id= p.id
    WHERE c.user_id = ? /* where ? is the current user's id */
    

    我冒昧地修改了查询以让数据库为我们返回 line_item_total。

    现在进入第二个查询,为第一个查询返回的每条记录运行 -

    SELECT COUNT(product_id)
    FROM cart
    WHERE product_id='$product_id'
    GROUP BY product_id
    

    我不太确定这应该做什么,但它不会像你期望的那样工作。它将返回购物车中有此 product_id 的用户的 COUNT 个。唯一相关的数量应该是您的购物车查询已经返回的数量。

    这绝对不漂亮,但应该足以让你开始 -

    <?php
    
    $current_user_id = 1; // coming from session or ...
    
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $link = mysqli_connect('host', 'user', 'pass', 'db');
    
    /* This is a very crude piece of code to handle the AJAX request. The user_id
     * predicate in the UPDATE query is really important to stop people modifying
     * the request to update someone else's cart */
    if (isset($_POST['action']) && $_POST['action'] == 'updateCartItem') {
        // Notice the three placeholders used for the prepared statement
        $stmt = mysqli_prepare($link, 'UPDATE cart SET quantity = ? WHERE id = ? AND user_id = ?');
        mysqli_stmt_bind_param($stmt, 'iii', $_POST['quantity'], $_POST['id'], $current_user_id);
        mysqli_stmt_execute($stmt);
        echo (mysqli_affected_rows($link) == 1) ? 'success' : 'failure';
        die;
    }
    
    /* Query to retrieve cart and associated products for given user_id  */
    $sql = 'SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price, c.quantity * p.sale_price AS line_item_total
    FROM cart AS c
    JOIN product AS p ON c.product_id = p.id
    WHERE c.user_id = ?';
    
    $stmt = mysqli_prepare($link, $sql);
    mysqli_stmt_bind_param($stmt, 'i', $current_user_id);
    mysqli_stmt_execute($stmt);
    
    $result = mysqli_stmt_get_result($stmt);
    $cart_items = mysqli_fetch_all($result, MYSQLI_ASSOC);
    
    ?>
    
    <div class="modal fixed-right fade" id="modalShoppingCart" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-vertical" role="document">
            <div class="modal-content">
                <ul class="list-group list-group-lg list-group-flush">
                    <?php $cart_total = 0; foreach ($cart_items as $cart_item): ?>
    
                        <li class="list-group-item cart-item">
                            <span class="cart-item-id"><input type="hidden" name="id" value="<?php echo $cart_item['id']; ?>"></span>
                            <span class="cart-item-img"><img src="../assets/img/<?php echo $cart_item['thumbnail']; ?>"></span>
                            <span class="cart-item-name"><?php echo $cart_item['name']; ?></span>
                            <span class="cart-item-price"><?php echo $cart_item['sale_price']; ?></span>
                            <span class="cart-item-quantity"><input type="number"  name="quantity[<?php echo $cart_item['product_id']; ?>]" value="<?php echo $cart_item['quantity']; ?>"></span>
                            <span class="cart-item-total"><?php echo $cart_item['line_item_total']; ?></span>
                        </li>
    
                    <?php $cart_total += $cart_item['line_item_total']; endforeach; ?>
                </ul>
    
                <div class="modal-footer line-height-fixed font-size-sm bg-light mt-auto">
                    <strong>Total</strong> <span id="cart-total-price" class="ml-auto"><?php echo $cart_total; ?></span>
                </div>
    
                <div class="modal-body">
                    <a class="btn btn-block btn-dark" href="checkout.php">Checkout Pesanan</a>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    $(document).ready(function() {
        $('.cart-item-quantity input').change(function() {
            updateQuantity(this);
        });
    
        /* Update quantity */
        function updateQuantity(quantityInput) {
            /* Calculate line price */
            var productRow = $(quantityInput).closest('li.cart-item');
            var cartItemId = productRow.find('.cart-item-id input').val();
            var price = parseFloat(productRow.find('span.cart-item-price').text());
            var quantity = $(quantityInput).val();
            var linePrice = price * quantity;
            productRow.find('span.cart-item-total').text(linePrice.toFixed(2));
    
            /* Send AJAX request to update line item */
            $.post( '', { action: 'updateCartItem', id: cartItemId, quantity: quantity })
                .done(function( data ) {
                    /* Their should be proper handling of the response here */
                    console.log( "Result: " + data );
                });
            updateCart();
        }
    
        function updateCart() {
            var cartTotal = 0;
            $('span.cart-item-total').each(function () {
                cartTotal += parseFloat($(this).text());
            });
            $('span#cart-total-price').text(cartTotal.toFixed(2));
        }
    });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多