0

I want to set a variable for a particular page. Whenever that page is loaded that value should get increment. I want to do without using session or application scope is there any other better option for this.

If i assign a variable whenever page is get loaded its automatically initialized how to avoid this.


apologize for not given complete details.

If any other url has clicked the value should initialize.

Please let me know.

Monicka Akilan
  • 1,501
  • 5
  • 19
  • 42

3 Answers3

1

Try using jQuery Cookie

$(document).ready(function(){
var count=parseInt($.cookie('the_page_count_cookie'),10);

$.cookie('the_page_count_cookie', count+1); 

});
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
1

Use cookies. There's an excellent cookie wrapper plugin for jQuery. https://github.com/carhartl/jquery-cookie

This is how you it.

Add this between your <head> and </head> tags:

<script src="/path/to/jquery.cookie.js"></script>

Now the usage looks like this (for your use case - add this to every page):

<script type="text/javascript">

$(document).ready(function()
{
    // Get Cookie Value
    var currentCount = $.cookie('myPageCounter');

    // Create Cookie, if the cookie doesn't exist
    if (!currentCount) {
        $.cookie('myPageCounter', 1);
    }

    // Otherwise, increment the cookie counter
    else {
        $.cookie('myPageCounter', (currentCount + 1));
    }
});

</script>
Latheesan
  • 23,247
  • 32
  • 107
  • 201
0

You could use localStorage, e.g.

localStorage['yourVarname'] = yourFunctionResult;

As long as you trust your users are using modern browsers (localStorage is supported by Firefox 3.5+, Safari 4+, IE8+, and Chrome). Otherwise you have a few options, two of which you don't want to use, so your left with cookies (another person gave details for that so I'll not elaborate) or another option is, as outlined here: Is it possible to create a variable, that doesn't change on refresh the page, in javascript?:

Pass data to the URL and read the current URL (including the data that you passed) when the page loads. For example: Redirect the browser to http://something.com/yourpage.html#flag=true if the user refreshed through the browser or redirect to http://something.com/yourpage.html#flag=false if the user clicked the button. On the onload of the page just read the current URL and see what the flag is.

Community
  • 1
  • 1
spacebean
  • 1,554
  • 1
  • 10
  • 13
  • isn't `localStorage` for HTML5? How would the user then deal with people visiting his site from older browsers? Cookie is cross platform and supported in every browser (if enabled of course). – Latheesan Oct 24 '13 at 11:46