-5

I have a bootstrap website and I stock user information in cookies with the plugin JS-cookie.

Can I show the value of the cookie in the HTML with classic JS/Jquery or do I have to use a framework like Angular ?

EDIT :

I use js-cookie https://github.com/js-cookie/js-cookie

So my code is, in the head page :

         <script>Cookies.set('money', '200', { expires: 7 });</script>

and in the body :

       <p> You have  <script>Cookies.get('money')</script> dollars </p>
Samuel-Zacharie Faure
  • 1,047
  • 11
  • 26
  • Have you tried just using a cookie value like any other value that you might use in jQuery? Did that not work? – zero298 Feb 08 '16 at 23:35
  • 2
    short answer: yes. unwanted answer: yes, but don't. cookies are for your server, and are sent automatically with every single http request. If you're pretending the cookie is a user setting, do your user profile management properly. Use the cookie for login status only, then consult the user database (via an API or whatever) to get the data you actually want to *show* on your site. – Mike 'Pomax' Kamermans Feb 08 '16 at 23:35
  • 1
    If cookies were only meant for the server there wouldn't be a [client-side API](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) for them. Some client-side only apps can use cookies effectively as a semi-persistent storage mechanism. One could also use [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). – Trevor Feb 08 '16 at 23:43

2 Answers2

3

You don't just insert a script in the middle of HTML to get the result of a function. The script has to perform an operation to put a value into the DOM.

<p You have <span id="amount"></span> dollars </p>
<script>
var amount = Cookies.get('money');
document.getElementById('amount').textContent = amount;
</script>
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

In native JavaScript, you can do the following. Note: this doesn't seem to work on Stackoverflow because of a security restriction, but it does seem to work in CodePen.

var arr = document.cookie.split(';'),
    cookies = {};
for(var i=0; i < arr.length; i++){
  var parts = arr[i].split('=');
  if(parts.length !== 2) continue;
  cookies[parts[0].trim()] = parts[1];
}
console.dir(cookies)

document.getElementById('out').textContent = cookies['myCookieKey'];
<div id="out"></div>

Update

Using the JS-Cookie code:

<p>You have <span id="amount"></span> dollars</p>

<script>
document.getElementById('amount').textContent = Cookies.get('money');
</script>
Trevor
  • 13,085
  • 13
  • 76
  • 99
  • 1
    Don't use `innerText`, it's not standard and Firefox doesn't support it. Use `textContent`. – Barmar Feb 09 '16 at 01:49