Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, guys when I try to add item to EMPTY CART(empty session) asynchronously it adds the item but does not display quantity in the #counter element. But if I refresh the page the quantity appears in #counter and from there I can add items asynchronously no problems. I'm pretty sure the problem is, that session::basket variable isn't initialised for the first request. but how do I resolve it? What am I missing?

What I have tried:

controller code:
PHP
$newBasket = new Basket($previousBasket);
$newBasket->addProduct($product, $product->id);

Session::put('basket', $newBasket);
$qtny = Session::get('basket') ? Session::get('basket')->quantity : 0;
return response()->json(['added' => $qtny], 200);


JavaScript
$.ajax({
    type: "GET",
    url: "/product/add-to-basket/"+id,
    dataType: "json",
    data: { id: id }
  })
  .done(function(data) {
     //var ob = JSON.parse(JSON.strigify)
     $('#counter').html(data['added']);
     swal("Added to basket!");
  });
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900