skip to Main Content

I have my shopping cart, and for adding to cart i’m using ajax. It works, but I don’t know how to update total quantity number which located at the header. There is no inputs with a field for selection of quantity, I want it to increase after each pushing button "add to cart" by 1 (with ajax). How can I do that?

CartController:

  public function addCart(Request $request, $id){
    $product = Product::find($id);
    $oldCart = Session::has('cart') ? Session::get('cart') : NULL;
    $cart = new Cart($oldCart);
    $cart->add($product, $product->id);

    $request = Session::put('cart', $cart);

    Session::flash('add-product', $product->name);

    return redirect()->back();
  }

Custom Cart class that contains the main logic:

public function add($item, $id){
      $storedItem = [
        'qty' => 0,
        'id' => $item->id,
        'prod_url' => $item->url,
        'code_cat' => $item->category->code,
        'url_cat' => $item->category->url,
        'name' => $item->name,
        'cost' => $item->price,
        'price' => $item->price,
        'img' => $item->cardImage->path
      ];
      if($this->items){
        if(array_key_exists($id, $this->items)){
          $storedItem = $this->items[$id];
        }
      }
        $storedItem['qty']++;
        $storedItem['cost'] = $item->price * $storedItem['qty'];
        $this->items[$id] = $storedItem;
        $this->totalQty++;
        $this->totalPrice += $item->price;
    }

AddToCart button:

<div class="product-icon-container">
  <a href="{{ route('basket-add', [ 'id' => $item->id ]) }}" class="scrollOffset btn btn-success mt-2 mb-1">Add to Cart</a>
  <a href="#" class="btn btn-danger mt-2 mb-1">Buy now!</a>
</div>

Total quantity in header:

<span class="prodcount">{{ Session::has('cart') ? Session::get('cart')->totalQty : '0' }}</span><i class="fas fa-shopping-basket"></i><span class="basket-text">Cart</span>

Simple ajax request:

$(document).ready(function() {
 $('.product-icon-container').find('a.scrollOffset').click(function (event){
   event.preventDefault();
   $.ajax({
      url: $(this).attr('href')
   });
  return false;
 });
});

2

Answers


  1. Chosen as BEST ANSWER

    My question was completely solved by a user from the Russian-speaking StackOverflow at the link.

    As an option, you can get a good solution by slightly changing @HEL Mab's code.

    $(document).ready(function() {
          $('.product-icon-container').find('a.scrollOffset').click(function (event){
            event.preventDefault();
            let totalQty = parseInt($('.prodcount').text());
            $.ajax({
    
            url: $(this).attr('href'),
            success: function (data, status, xhr) {
              // onReponseSuccess
              totalQty++;
              $('.prodcount').text(totalQty);
            },
            error: function(jqXhr, textStatus, errorMessage) {
              // handle onReponseError
            }
        });
      });
    });
    

  2. In your add() method, you need to return the result of the updating qty.

    public function add($item, $id){
          // your code
        return response()->json(['success' => true]);
    }
    

    and then in your ajax request, it has a success function to check the request is successful or not.

    $.ajax({
          url: $(this).attr('href'),
        success: function (data, status, xhr) {
          // onReponseSuccess
          $('.prodcount').text(your_qty)
        },
        error: (jqXhr, textStatus, errorMessage) {
          // handle onReponseError
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search