Aymen Kareem Aymen Kareem - 1 month ago 15
Javascript Question

Why session and cookies in javascript didn't work?

I'm learning sessions and cookies in JavaScript. I have a form that takes some data and store it in session and cookies variables to be displayed in another page (second page) as follows:

<html>
<body>
<form action="second.html" onsubmit="return myFunction();">
Enter a session variable: <input id="sess" type="text" />
</br>
Enter a coockie variable: <input id="cookiess" type="text" />

</br>
<input type="submit" />
</form>

<script>
function myFunction() {
document.cookie = "username="+document.getElementById("cookiess").value + "; expires=Fri, 14 Oct 2016 12:00:00 UTC";
sessionStorage["myKey"] = document.getElementById("sess").value;

return true;
}

</script>
</body>
</html>


and this is the second.html page:

<html>
<body>

<script>

alert(sessionStorage["myKey"] + document.cookie);
</script>
</body>
</html>


However, when I display the session and cookie variables in the alert function, it display empty variables. Why my session and cookies variables don't work?

Answer

Hi if you want to check how session storage works you can see the below code... its for a single page.

if 2 pages are there If you're just running this from a file:// protocol, it won't work

  <!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (sessionStorage.clickcount) {
            sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
           sessionStorage["myKey"] = sessionStorage.clickcount;
        } else {
            sessionStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session."+sessionStorage["myKey"];
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>
Comments