第二次ajax调用后值不刷新

时间:2017-08-25 17:57:36

标签: jquery ajax

我正在进行ajax调用并使用jQuery呈现购物车。

function show_cart() {

    $.ajax({
        url: 'functions/show-cart.php',
        type: 'POST',
        dataType: 'json',
    })

    .done(function (data) {
        $.each(data.cart, function (index, item) {

            var showCart = `

                <div class="row hr marg-b-30 marg-t-30">
                        <div class="col-md-2 col-sm-2 col-xs-12 marg-b-30">
                            <img src="uploads/${item.pic_name}" alt="${item.product_name}" class="">
                        </div>
                        <div class="col-md-5 col-sm-5 col-xs-12 marg-b-30">
                            <a href="#" class=""><b>Product</b></a><b class="right">R${item.price}</b>
                            <p class="">${item.product_name}</p>
                            <button class="btn btn-xs bg-color--second removeItem" data-id="${item.item_id}" data-itr="${item.i}">Remove <i class="material-icons">delete</i></button>

                        </div>
                        <div class="col-md-3 col-sm-3 col-xs-12 marg-b-30">
                            <div class="input input-counter">
                                <div class="input__helper pos-left pointer input-counter__plus cartPlus" data-itr="{$i}">
                                    <i class="material-icons ico-xs"></i>
                                </div>
                                <input type="text" class="text-center" readonly="" value="${item.each_item}">
                                <div class="input__helper pointer input-counter__minus">
                                    <i class="material-icons ico-xs"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2 col-sm-2 col-xs-12 marg-b-30 text-right text-left-xs">
                            <span class="price-xs">R${item.subtotal}</span>
                        </div>
                    </div>`;

            $(".somediv").append(showCart);


        });

        $("#total").append(data.total);
        $("#subtotal").append(data.total);


    })

    .fail(function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus + ': ' + errorThrown);
        console.warn(jqXHR.responseText);
    });
}

购物车中的每件商品都有一个删除/删除按钮,当用户点击它时,它会调用我的删除功能,该功能会从购物车中删除该商品(淡出)。然后我对同一个show-cart.php脚本进行ajax调用,该脚本最初显示购物车,希望这将更新小计值和总值,但它们保持与删除购物车项目之前相同。如何更新总数?

以下是删除项目或从购物车功能中删除:

function remove_item() {

    $("body").on("click", ".removeItem", function () {
        var id = $(this).data('id');
        var indexToRemove = $(this).data('itr');
        var div = $(this).parents("div.hr");
        $.ajax({
            url: 'functions/show-cart.php',
            type: 'POST',
            dataType: 'json',
            data: {
                indexToRemove: indexToRemove
            },
            beforeSend: function () {
                $(div).html("<img src='images/spinner.gif'>");
                $("#total").empty();
            },
        })

        .done(function (data) {
            $(div).fadeOut();
            $( "#total" ).html(data.total);//This gives me the same total as before I removed the item

        })

        .fail(function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
            console.warn(jqXHR.responseText);
        })
    })
} // END REMOVE ITEM

显示-cart.php

if(!isset($_SESSION['cart_array'])) {

    $itemsInCart = 0;

} else {

        $featured = "Yes";
        $cartTotal = "";
        $i=0;
        foreach($_SESSION['cart_array'] as $each_item) {
            $item_id = $each_item['item_id'];

            $stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?");
            $stmt->bind_param("is", $item_id, $featured);
            $stmt->execute();
            $result = $stmt->get_result();
            $numRows = $result->num_rows;
            if($numRows > 0) {
                while($row = $result->fetch_assoc()) {
                    $product_name = sanitize($row['product_name']);
                    $price = sanitize(money_format('%.2n', $row['price']));
                    $subtotal = money_format('%.2n', $each_item['quantity'] * $price);
                    $pic_name = $row['pic_name'];
                    $cartTotal = $subtotal + $cartTotal;
                    $quantity = $each_item['quantity'];

                    $cart_details[] = array(

                    "product_name" => $product_name,
                    "price" => $price,
                    "subtotal" => $subtotal,
                    "pic_name" => $pic_name,
                    "each_item" => $quantity,
                    "subtotal" => $subtotal,
                    "item_id" =>$item_id,
                    "i" => $i

                    );

                    $i++;
                }
            }

            $stmt->close();
        }



    $response['total'] = $cartTotal;
    $response['cart'] = $cart_details;
    echo json_encode($response);
}


if(isset($_POST['indexToRemove']) && $_POST['indexToRemove'] !== "") {

        $key_to_remove = $_POST['indexToRemove'];
        if(count($_SESSION['cart_array']) <=1) {
            unset($_SESSION['cart_array']);
        } else {

            unset($_SESSION['cart_array']["$key_to_remove"]);
            sort($_SESSION['cart_array']);
        }
    }

1 个答案:

答案 0 :(得分:0)

在返回ajax响应之前,您应该从会话中取消设置项目。试试这个:

if(isset($_POST['indexToRemove']) && $_POST['indexToRemove'] !== "") {

            $key_to_remove = $_POST['indexToRemove'];
            if(count($_SESSION['cart_array']) <=1) {
                unset($_SESSION['cart_array']);
            } else {

                unset($_SESSION['cart_array']["$key_to_remove"]);
                sort($_SESSION['cart_array']);
            }
        }    

if(!isset($_SESSION['cart_array'])) {

        $itemsInCart = 0;
        $response['total'] = 0;
        echo json_encode($response);

    } else {

            $featured = "Yes";
            $cartTotal = "";
            $i=0;
            foreach($_SESSION['cart_array'] as $each_item) {
                $item_id = $each_item['item_id'];

                $stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?");
                $stmt->bind_param("is", $item_id, $featured);
                $stmt->execute();
                $result = $stmt->get_result();
                $numRows = $result->num_rows;
                if($numRows > 0) {
                    while($row = $result->fetch_assoc()) {
                        $product_name = sanitize($row['product_name']);
                        $price = sanitize(money_format('%.2n', $row['price']));
                        $subtotal = money_format('%.2n', $each_item['quantity'] * $price);
                        $pic_name = $row['pic_name'];
                        $cartTotal = $subtotal + $cartTotal;
                        $quantity = $each_item['quantity'];

                        $cart_details[] = array(

                        "product_name" => $product_name,
                        "price" => $price,
                        "subtotal" => $subtotal,
                        "pic_name" => $pic_name,
                        "each_item" => $quantity,
                        "subtotal" => $subtotal,
                        "item_id" =>$item_id,
                        "i" => $i

                        );

                        $i++;
                    }
                }

                $stmt->close();
            }



        $response['total'] = $cartTotal;
        $response['cart'] = $cart_details;
        echo json_encode($response);
    }