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.
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.
You can't access cookies from a different path - otherwise it would be a security hole.
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=/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With