2

So I'm implementing a small badge in my header indicating how many items the user has in his cart..

This is how I've thought of doing it: Set the badge value on user log in and then just increment/decrement it when the user adds/removes from his cart.

I tried setting the value in jquery on my index page like this:

function loadCartBadgeVal(id) {
$.getJSON(`/Cart/GetCartCount?customerId=${id}`,
    function (data) {
        $("#cart-badge").text('' + data);
    }); 
}

This works but when I redirect to another page my badge value resets to 0 .. my badge is implemented in a partial view like this:

<span class="badge badge-info" id="cart-badge"></span>
J.Kirk.
  • 943
  • 3
  • 12
  • 32
  • are you calling the `loadCartBadgeVal` on the page where you redirect to , you need to load the value on every page. – Muhammad Omer Aslam Dec 25 '17 at 13:11
  • Does this mean I need to do a database call every single time? Is there no better way to do that? – J.Kirk. Dec 25 '17 at 13:12
  • 1
    so u better save it in the session, cookies, localstorage etc – plonknimbuzz Dec 25 '17 at 13:14
  • if you are using this count to show only the items in the cart you do not need to use the databases, if I would have to do it via javascript I would use `localStorage` to hold the values temporarily until checked out. that way i just need to call the session variable on every page and nothing else – Muhammad Omer Aslam Dec 25 '17 at 13:14

1 Answers1

3

You can use localStorage to save the cart items count and show it anywhere on your site/app.

The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().

localStorage.setItem('cartCount', 1);

The syntax for reading the localStorage item is as follows:

var count= localStorage.getItem("cartCount");

The syntax for removing the localStorage item is as follows:

localStorage.removeItem("cartCount");
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
  • Thank you for your answer @Muhammad. This might be a totally new question but why localStorage over a Sessionvariable? – J.Kirk. Dec 25 '17 at 13:20
  • 1
    Well, `localStorage` and `sessionStorage` both extend `Storage` . There is no difference between them except for the intended "non-persistence" of `sessionStorage`. That is, the data stored in `localStorage` persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site. see this [post](https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies) @J.Kirk. – Muhammad Omer Aslam Dec 25 '17 at 13:23