2

I have the following code

<html>
    <head>
        <script>
            var m=0;
            function add() {
                m++;
            }
        </script>
    </head>
    <body>
        <button onclick="add();">click</button>
    </body>
</html>  

But if I refresh the page then again the value of m starts from 0. How can I persist the value of m between each load of the page on a client machine?

slugster
  • 49,403
  • 14
  • 95
  • 145

6 Answers6

3

One way is cookie

document.cookie = 'foo,bar'

Another way to do is use localstorage

localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // return 'bar'
lostyzd
  • 4,515
  • 3
  • 19
  • 33
2

you can use cookies from javascript. check this link.

http://www.w3schools.com/js/js_cookies.asp

here is the working code sample:

<html> 
<head> 
<script> 
var m=getCookie("m");
if(isNaN(m)) {
    m=0;
}
function add() 
{
    m++;
    alert(m);
    setCookie("m",m,86400);
} 

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
    {
            return unescape(y);
        }
    }
}
</script> 
<body>
<button onclick="add();">click</button> 
</body> 
</html> 
Emir Akaydın
  • 5,708
  • 1
  • 29
  • 57
1

Actually it is what js mean to do on browsers, don't fight it, live with it. If you want to store variables in browsers, use cookies or local-storage(html5) then.

OpenGG
  • 4,345
  • 2
  • 24
  • 31
1

You might have to use:

  1. setting cookies by your backend script.
  2. use session in your backed script. eg session_start,$_SESSION in PHP
  3. use localStorage , that will work only in HTML 5 supporting browsers though.
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
0

You can't do that. The DOM and all the JS variables in your page get recreated on refresh. If you want to persist it you can either use cookies or localstorage to persist it.

Community
  • 1
  • 1
JohnP
  • 49,507
  • 13
  • 108
  • 140
0

It's normal that refreshing the page loads javascript functions again - use sessions or cookies to store variables like that.

evilone
  • 22,410
  • 7
  • 80
  • 107