即使购物车中有商品,“也无法删除商品。购物车为空”

时间:2019-07-22 21:10:52

标签: ajax shopping-cart laravel-5.8 php-7.2

我是网络编程的新手。最近,我试图建立一个电子购物项目,并将购物车中的可移除物品卡住。

我有 views / cart / list.blade.php ,带有菜单和两个ajax代码,用于更新和删除功能。点击删除按钮后,页面显示错误框响应:“ 删除失败。此购物车中没有任何物品”,这是在 Cartcontroller.php 中设置的。我认为这意味着代码可以工作,但无法在购物车中检索数据。我再次检查了一次,但是由于知识和经验的限制,我无法解决此问题。这就是为什么我想从我们友好的专业编码器那里寻求帮助。 PS :我也使用Firefox检查功能,但除了绿色状态为200之外什么都没找到。

这是list.blade.php

<?php $total = 0; ?>
@forelse($carts as $cart )
<?php $total += $cart['product_quantity'] * $cart['product_price'] ; ?>
<tr>
  <td><img src="{{asset('../storage/app/public/product/' . $cart['product_image'])}}" alt="" style="width:100px"></td>
  <td>{{$cart['product_name']}}</td>
  <td>{{number_format($cart['product_price'])}}</td>
  <td><input name="txtquantity" class="txtquantity" id="txtquantity" type="number" min="1" value="{{$cart['product_quantity']}}" required pattern="[0-9]{1,3}" title="Quantity has to be a number and have less than 4 digit"/></td>
  <td>{{number_format($cart['product_quantity'] * $cart['product_price'])}} 
  </td>
  <input type="hidden" name="product_id" data-id="product_id" id="product_id" value="{{ $cart['product_id'] }}">
  <td>
  <button type="button" class="btn btn-success btnUpdateCart" data-id= "{{$cart['product_id']}}"><i class="fa fa-refresh"></i></button>
  </td>
  <td>
   <button type="button" class="btn btn-danger btnDeleteCart" data-id={{$cart['product_id']}}"><i class="fa fa-remove"></i></button>
  </td>
  </tr>
@empty
<tr>
<td colspan="5">Không có sản phẩm</td>
</tr>
@endforelse

//Ajax For Update and Delete

<script type="text/javascript">
    function deleteCart() {
        alert(12);
    }
    $(document).ready(function() {
        $(".btnUpdateCart").click(function(e) {
            let product_quantity = $(this).parent().parent().find("#txtSoLuong").val();
            let product_id = $(this).data('product_id');
            $.ajax({
                url: '{{url("cart/update")}}',
                type: "POST",
                dataType: 'json',
                data: {product_id: product_id, product_quantity: product_quantity, _token: "{{csrf_token()}}"},
                success: function(result) {
                    if (result.status == 1) {
                        alert(result.message);
                    }
                    else {
                        alert(result.message);
                    }
                },
                error: function(error) {
                    alert("Không cập nhật được");
                }
            });
        });

        $('.btnDeleteCart').click(function(e) 
        {
            let product_id = $(this).data('product_id');
            if(confirm("Bạn chắc chắn xóa sản phẩm này?")) 
            {
                $.ajax({
                        url: '{{url('cart/remove')}}',
                        type: 'POST',
                        dataType: 'json',
                        data:{ 
                                product_id: product_id,
                                 "_token": '{{csrf_token()}}'
                            },
                        success: function(result){
                            if (result.status == 1){ 

                                alert(result.message);
                                window.location.reload(true);
                            }
                            else {
                                alert(result.message);
                            }
                        },
                        error: function(error) {
                            alert("Không xóa được");
                        }
                    });
            }

        });
    });
</script>
@endsection

这是web.php:

//Cart Area for Item

Route::get("cart/list","\App\Http\Controllers\CartController@list_cart");
Route::post("cart/add", "\App\Http\Controllers\CartController@add_cart"); 
Route::post('cart/update',"\App\Http\Controllers\CartController@update_cart");
Route::post('cart/remove',"\App\Http\Controllers\CartController@remove_cart");

//End of Cart for Item

此CartController.php:

<?php
namespace App\Http\Controllers;
session_start();

use Illuminate\Http\Request;
use App\Helper\Cart;
use App\Models\Product;
use Illuminate\Http\Response;

class CartController extends Controller
{
   public function add_cart(Request $request) {
    $product_id = $request->post('product_id');
    $product_quantity = $request->post("txtSoLuong");
    $product = Product::findOrFail($product_id);
      if (isset($product)) {
            $item   = [
                'product_name' => $product->product_name,
                "product_id" => $product->product_id,
                "product_image" => $product->product_image,
                "product_price" => $product->product_price,
                "product_quantity" => $product_quantity
            ];
            Cart::getInstance()->addCart($product_id, $item);
            return redirect(url("cart/list"))->with("success", "Successful adding item");
        }
        return redirect("/");

//Removing Item in Cart

public function remove_cart(Request $request) {
    $product_id = $request->post('product_id');
    $remove = Cart::getInstance()->removeCart($product_id);
       if ($remove) {
        return Response()->json([
                'status' => 1,
                'message' => "Remove Successful",
            ]);
        }
        return Response()->json([
            'status' => 0,
            'message' => "Remove Fail. There is no item in this cart",
        ]);
    }

这是Cart.php:

<?php 
namespace App\Helper;

class Cart
{
    public static function getInstance() {
        return new static();
    }
    public function addCart($product_id, $item) {
        $cart = $this->getCart($product_id);

        if (empty($cart)) {
            $cart = [
                "product_name" => $item['product_name'],
                "product_quantity" => $item['product_quantity'],
                "product_id" => $item['product_id'],
                "product_price" => $item['product_price'],
                "product_image" => $item['product_image']
            ];
        }
        else {
            $product_quantity = $cart['product_quantity'] + $item['product_quantity'];
            $cart['product_quantity'] = $product_quantity;
        }

        $this->setItemCart($product_id, $cart);
    }

// Remove Cart Function

public function removeCart($product_id) {
    $cart = $this->getItemCart($product_id);
       if (!empty($cart)) {
            unset($_SESSION['cart'][$product_id]);
            return true; 
        }
        return false;
    }

对于成功的功能,该项目将被删除,并显示“删除成功”的通知。

Firefox报告

Firefox Report for Status

0 个答案:

没有答案