Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cookie value from variable

I have been recently trying to set a cookie holding the user's name, it opens a prompt pop-up box asking for a new user name. When the user inserts the user name and clicks "ok" it doesn't treat the variable (sconName) as a variable and just puts "sconName".

Note: Scon is the name of the website.

Heres the only script I am using:

<html>
  <body>
<script>
function readCookie(name) { 
    var nameEQ = name + "="; 
    var ca = document.cookie.split(';'); 
    for(var i=0;i < ca.length;i++) { 
        var c = ca[i]; 
        while (c.charAt(0)==' ') c = c.substring(1,c.length); 
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); 
    } 
    return null; }
    </script>
<script>
  var username = readCookie('sconName');
if (username) {
   document.write("Your current username is: " + username);
}
  else {
    document.write("You have no user name");
  }

  function changeUsername() {
    var changedName=prompt("Enter user name.");
    if (changedName) {
document.cookie = 'sconName=changedName; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/'}}
  </script>
<button onclick="changeUsername()">Change</button>
</body>
</html>

Please can you explain how to tell the system that its a variable not just text. Thanks.

like image 283
Blob Avatar asked Jan 18 '13 15:01

Blob


People also ask

How do you set a variable in cookies?

Cookies can be set using setcookie() and setrawcookie() functions. Consider the example below in which a cookie variable is set for a month. This sign '/' indicates that the cookie is available for the entire website. We have used $_COOKIE variable to retrieve the value of cookie.

Can I set cookie for another path?

You can't access cookies from a different path - otherwise it would be a security hole.


1 Answers

javascript does not parse variables inside quotes. You need to break out of the quotes to use the variable:

document.cookie = 'sconName='+changedName+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/'
like image 184
Crayon Violent Avatar answered Oct 21 '22 11:10

Crayon Violent