duanba3707 2019-05-30 10:34
浏览 60

删除产品最终总数没有使用php ajax减少

I am creating a ecommerce site for my final year project. I am ran into the problem with delete the product . if I delete product product has been deleted from database success. but final total didn’t reduced what I tried so far I attached below along with screen shot image below.

enter image description here

Table

 <div class="container">
                <table class="table table-striped" id="mytable">
                    <thead>
                    <tr>
                        <th>ProductID</th>
                        <th>Productname</th>
                        <th>Price</th>
                        <th>Qty</th>
                        <th>Amount</th>
                        <th>Delete</th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>

        </div>

        <div style='text-align: right; margin:10px'>
            <label><h3>Total amount: </h3></label>
            <span style="font-size: 40px; color: #ff0911" id='total-amount'></span>
        </div>

Display the Products

<script> 
getProducts();
function getProducts() {
    $.ajax({
        type: 'GET',
        url: 'all_cart.php',
        dataType: 'JSON',
        success: function(data) {
            data.forEach(function(element) {
                var id = element.id;
                var product_name = element.product_name;
                var price = element.price;
                $('#mytable tbody').after
                (
                    '<tr> ' +
                    '<td>' + id + '</td>' +
                    '<td>' + product_name + '</td>' +
                    '<td>' + price + '</td>' +
                    "<input type='hidden' class='price' name='price' value='" + price + "'>" +
                    '<td>' + "<input type = 'text' class='qty' name='qty' value='1'/>" + '</td>' +
                    '<td>' + "<input type = 'text' class='amount' id='amount' disabled/>" + '</td>' +

                    '<td>' +  " <Button type='button' class='btn btn-primary' onclick='deleteProduct(" + id + ")' >Delete</Button> " + '</td>' +
                    '</tr>');
            });
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

delete product function

function deleteProduct(id) {
    $(this).find('deleteProduct').click(function(event) {
        deleteProduct($(event.currentTarget).parent('tr'));
    });
    var total = 0;
    $('.amount').each(function(e){
        total -= Number($(this).val());
    });
    $('#total-amount').text(total);
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });
}
</script>

remove.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include "db.php";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $stmt = $conn->prepare("delete from cart where id=?");
    $stmt->bind_param("s", $id);
    $id = $_POST["id"];
    if ($stmt->execute())
        {
            echo 1;
        }
    else 
        {
                echo 0;
        }
        $stmt->close();
        }
?>
  • 写回答

1条回答 默认 最新

  • doufang2023 2019-05-30 10:57
    关注

    I think your issue is js-related more then php related. Since the remove.php files looks fine you may have a problem with AJAX.

    function deleteProduct(id) {
    $(this).find('deleteProduct').click(function(event) {
        deleteProduct($(event.currentTarget).parent('tr'));
    });
    

    This looks weird already since you're using jquery "find" on a non-class. Maybe u forgot a dot? Should be $(this).find(".deleteProduct").... and if u do so remember to actually add the class.

    Beside this when you delete your product via ajax you are never refreshing the table, so the product-row will still be present. When you calculate your total you are fetching your current table elements:

     var total = 0;
    $('.amount').each(function(e){
        total -= Number($(this).val());
    });
    

    this will lead to incorrect values if you don't delete the row u're pressing delete onto.

    $('#total-amount').text(total);
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
    
                    }
                });
    

    You should add to the success callback function the part where you are calculating totals, but before that, you should delete the table row with something like $("....").remove();

    Edit with correct code: First of all bring the jquery delete button listener out of your delete function and make it like this:

    <script>
         $('.mydeletebtn').click(function(event) {
        deleteProduct($(this).data("rowid"));
        });
        function deleteProduct(id) {
         .....
        }
    

    Then modify the HTML output for the delete row changing it like this:

    '<td>' +  " <Button type='button' class='mydeletebtn btn btn-primary' data-rowid="'+id+'" >Delete</Button> " + '</td>' +
    

    since you don't really need the onclick when u're using jquery. I modified it so that your rowid is passed as javascript data-attribute.

    After all of this you need to actually handle the row delete + total update like this:

        var $parentRow = $(this).closest("tr");
                    $.ajax({
                        type: 'POST',
                        url: 'remove.php',
                        dataType: 'JSON',
                        data: {id: id},
                        success: function (data) {
                            $parentRow.delete();
                            updateTotals();
                        },
                        error: function (xhr, status, error) {
                            alert(xhr.responseText);
    
                        }
                    });
    

    Your final JS should be something like this:

    <script>
    function updateTotals(){
    var total = 0;
        $('.amount').each(function(e){
            total -= Number($(this).val());
        });
    $('#total-amount').text(total);
    }
    $('.mydeletebtn').click(function(event) {
            deleteProduct($(this).data("rowid"),$(this));
            });
    function deleteProduct(rowid,$row) {
             var $parentRow = $(this).closest("tr");
                        $.ajax({
                            type: 'POST',
                            url: 'remove.php',
                            dataType: 'JSON',
                            data: {id: rowid},
                            success: function (data) {
                                $parentRow.delete();
                                updateTotals();
                            },
                            error: function (xhr, status, error) {
                                alert(xhr.responseText);
    
                            }
                        });
            }
    
    </script
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100