Answers.Body: <p>The cookie that Craft Commerce uses for cart/session management is set using Craft's <code>craft()-&gt;userSession-&gt;saveCookie</code>, which hard-codes cookie's <code>httpOnly</code> flag, meaning it can't be accessed by JavaScript.</p>
  
  <p>If you want to pull of what you're trying to do, you'll need to use something like the <a href="https://github.com/lewisjenkins/craft-lj-cookies/" rel="nofollow">LJ Cookies</a> or <a href="https://straightupcraft.com/craft-plugins/cookies" rel="nofollow">Cookies</a> plugin to add and ready your own cookie according to your business logic.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-02-04T20:42:06.147Z
Answers.Text: Thanks Brad! I've updated my question with what I came up with in case someone stumbles across this question.
Answers.UserDisplayName: Damon
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-01-31T18:27:37.023Z
Answers.LastActivityDate: 2016-01-31T18:27:37.023Z
Answers.UserDisplayName: Brad Bell
Body: <p>Within my application, I would like to only show a link to the the user's cart only if there are products in it.</p>
  
  <p>I was going to use javascript to check the cookie I can see getting set. <code>commerce_cookie</code></p>
  
  <p>The problem I'm having is how to read that cookie. I realize its encrypted &amp; I'm not accessing the cookie correctly. That's why I'm unable to get and check for any orders. Is there a better way to check the cart dynamically in this way?</p>
  
  <p>I am trying to read it like this:</p>
  
  <pre><code>var cart = getCookie('commerce_cookie');
  
  console.log(cart);  // false
  
  // check if there are any products in the cart
  if (cart) {
     // show the cart icon
  } else {
      // hide the cart icon
  }
  
  function getCookie(cookie) {
      if ($.cookie(name)) {
          returnJSON.parse($.cookie(name));
      }
  }
  </code></pre>
  
  <p>I have read through <a href="https://github.com/lewisjenkins/craft-lj-cookies/" rel="nofollow">this thread</a> about LJ Cookies, but I'm still not confident I'm looking for the cookie correctly:</p>
  
  <pre><code>{{ craft.lj_cookies.get( 'commerce_cookie' ) }}
  </code></pre>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>What I was tying to do was hide the cart icon and only show it (along with item quantity) <em>only</em> if there were items in the cart.</p>
  
  <p>To do this, you'll need a plugin to listen for the <code>onBeforeAddToCart</code> event.</p>
  
  <p><strong>MyPlugin.php</strong></p>
  
  <pre><code>// Listen for items getting added to the cart.
  craft()-&gt;on('commerce_cart.onBeforeAddToCart', function (Event $event) {
      $cart = craft()-&gt;commerce_cart-&gt;getCart();
      // set expire &amp; other params as needed
      $cookie = new HttpCookie('totalQty', $cart-&gt;totalQty);
      craft()-&gt;request-&gt;getCookies()-&gt;add($cookie-&gt;name, $cookie);
  });
  </code></pre>
  
  <p>Then I've got an ajax request that will check if that cookie exists.</p>
  
  <p><strong>jquery</strong></p>
  
  <pre><code>var data = {
      'CSRF': $('input[name="CSRF"]').val()
  };
  
  $.ajax({
      'type': 'post',
      'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
      'cache': false,
      'data': data,
      'url': '/actions/myplugin/checkCookie',
      'dataType': 'json',
      'timeout': 50000
  }).done(function (response) {
      // handle response
  }).fail(function (error) {
     // Total fail.
  });
  </code></pre>
  
  <p>That routes to a controller method within my plugin:</p>
  
  <p><strong>MyPlugin.php</strong></p>
  
  <pre><code>if (craft()-&gt;request-&gt;isAjaxRequest()) {
      return $this-&gt;returnJson(craft()-&gt;request-&gt;getCookie('totalQty'));
  }
  </code></pre>
  
  <p>Here is how I am then handling/updating the UI with the results of that ajax request. I am summarizing my code here, there is more logic than I am listing - just trying to keep the size of this thread below the level of "book".</p>
  
  <p>I am using velocity for my transitions.</p>
  
  <p><strong>jquery</strong></p>
  
  <pre><code> ...
   var qty = (result.value + 1);  // value is zero-based array so +1
  
    $('#icon').velocity('fadeIn', {
        'duration': 300,
        'display': 'inline-block',
        'complete': function () {
            $('&lt;div/&gt;', {
                'id': 'cartQty',
                'text': qty
            }).appendTo($('#icon'))
                .velocity('transition.bounceIn', {
                    'duration': 300,
                    'easing': 'easeInOutSine'
                });
            }
        });
  </code></pre>
  
  <p>I wasn't able to find an event that listened for the Empty Cart event, so I had to get creative here.</p>
  
  <p>I listen for the "Empty Cart" form submit via jQuery. From there I make another ajax request to my plugin:</p>
  
  <p><strong>jQuery</strong></p>
  
  <pre><code>$('#emptyCartForm').submit(function (event) {
       deleteCookie(); // calls an ajax method (below)
  });
  
  
  $.ajax({
      'type': 'post',
      'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
      'cache': false,
      'data': data,
      'url': '/actions/myplugin/deleteCookie',
      'dataType': 'json',
      'timeout': 50000
  }).done(function (response) {
      // handle response
  }).fail(function (error) {
     // Total fail.
  });
  </code></pre>
  
  <p>That request makes a call to a controller method within my plugin:</p>
  
  <p><strong>MyPlugin.php</strong></p>
  
  <pre><code> if (craft()-&gt;request-&gt;isAjaxRequest()) {
       craft()-&gt;request-&gt;deleteCookie('totalQty');
       return $this-&gt;returnJson(['status' =&gt; 'success']);
  }
  </code></pre>
  
  <p>I'm happy to edit or please feel free to edit if there is any way I can improve this technique.</p>
  
Tags: <plugin-craftcommerce>
Title: How can I get/check the contents of a cart via javascript (cookie)?
ThreadText: # How can I get/check the contents of a cart via javascript (cookie)?
  
  (Asked by: username_0 on 2016-01-31)
  
  Within my application, I would like to only show a link to the the user's cart only if there are products in it.
  
  I was going to use javascript to check the cookie I can see getting set. `commerce_cookie`
  
  The problem I'm having is how to read that cookie. I realize its encrypted & I'm not accessing the cookie correctly. That's why I'm unable to get and check for any orders. Is there a better way to check the cart dynamically in this way?
  
  I am trying to read it like this:
  
  ```
  var cart = getCookie('commerce_cookie');
  
  console.log(cart);  // false
  
  // check if there are any products in the cart
  if (cart) {
     // show the cart icon
  } else {
      // hide the cart icon
  }
  
  function getCookie(cookie) {
      if ($.cookie(name)) {
          returnJSON.parse($.cookie(name));
      }
  }
  
  ```
  
  I have read through [this thread](https://github.com/lewisjenkins/craft-lj-cookies/) about LJ Cookies, but I'm still not confident I'm looking for the cookie correctly:
  
  ```
  {{ craft.lj_cookies.get( 'commerce_cookie' ) }}
  
  ```
  
  **SOLUTION**
  
  What I was tying to do was hide the cart icon and only show it (along with item quantity) *only* if there were items in the cart.
  
  To do this, you'll need a plugin to listen for the `onBeforeAddToCart` event.
  
  **MyPlugin.php**
  
  ```
  // Listen for items getting added to the cart.
  craft()->on('commerce_cart.onBeforeAddToCart', function (Event $event) {
      $cart = craft()->commerce_cart->getCart();
      // set expire & other params as needed
      $cookie = new HttpCookie('totalQty', $cart->totalQty);
      craft()->request->getCookies()->add($cookie->name, $cookie);
  });
  
  ```
  
  Then I've got an ajax request that will check if that cookie exists.
  
  **jquery**
  
  ```
  var data = {
      'CSRF': $('input[name="CSRF"]').val()
  };
  
  $.ajax({
      'type': 'post',
      'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
      'cache': false,
      'data': data,
      'url': '/actions/myplugin/checkCookie',
      'dataType': 'json',
      'timeout': 50000
  }).done(function (response) {
      // handle response
  }).fail(function (error) {
     // Total fail.
  });
  
  ```
  
  That routes to a controller method within my plugin:
  
  **MyPlugin.php**
  
  ```
  if (craft()->request->isAjaxRequest()) {
      return $this->returnJson(craft()->request->getCookie('totalQty'));
  }
  
  ```
  
  Here is how I am then handling/updating the UI with the results of that ajax request. I am summarizing my code here, there is more logic than I am listing - just trying to keep the size of this thread below the level of "book".
  
  I am using velocity for my transitions.
  
  **jquery**
  
  ```
   ...
   var qty = (result.value + 1);  // value is zero-based array so +1
  
    $('#icon').velocity('fadeIn', {
        'duration': 300,
        'display': 'inline-block',
        'complete': function () {
            $('<div/>', {
                'id': 'cartQty',
                'text': qty
            }).appendTo($('#icon'))
                .velocity('transition.bounceIn', {
                    'duration': 300,
                    'easing': 'easeInOutSine'
                });
            }
        });
  
  ```
  
  I wasn't able to find an event that listened for the Empty Cart event, so I had to get creative here.
  
  I listen for the "Empty Cart" form submit via jQuery. From there I make another ajax request to my plugin:
  
  **jQuery**
  
  ```
  $('#emptyCartForm').submit(function (event) {
       deleteCookie(); // calls an ajax method (below)
  });
  
  $.ajax({
      'type': 'post',
      'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
      'cache': false,
      'data': data,
      'url': '/actions/myplugin/deleteCookie',
      'dataType': 'json',
      'timeout': 50000
  }).done(function (response) {
      // handle response
  }).fail(function (error) {
     // Total fail.
  });
  
  ```
  
  That request makes a call to a controller method within my plugin:
  
  **MyPlugin.php**
  
  ```
   if (craft()->request->isAjaxRequest()) {
       craft()->request->deleteCookie('totalQty');
       return $this->returnJson(['status' => 'success']);
  }
  
  ```
  
  I'm happy to edit or please feel free to edit if there is any way I can improve this technique.
  
  **Tags:** plugin-craftcommerce
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2016-01-31. Score: 2 | Accepted answer
  
  The cookie that Craft Commerce uses for cart/session management is set using Craft's `craft()->userSession->saveCookie`, which hard-codes cookie's `httpOnly` flag, meaning it can't be accessed by JavaScript.
  
  If you want to pull of what you're trying to do, you'll need to use something like the [LJ Cookies](https://github.com/lewisjenkins/craft-lj-cookies/) or [Cookies](https://straightupcraft.com/craft-plugins/cookies) plugin to add and ready your own cookie according to your business logic.
  
  > **Comments:**
  > **username_0**: Thanks username_1! I've updated my question with what I came up with in case someone stumbles across this question.  
  
  ---
  
  