How to save a javascript variable - javascript

I have a javascript variable, which is incremented by a javascript function in a .php script, only problem is that the page reloads when the function is called, so I need some way of saving the variable to be the same when the page is either reloaded or whenever you enter it.
I know you can do a local save but I am not quiet sure if it saves the variable when you leave the website.
My variable is in a html script.
<script type="text/javascript">
var varNumber= 1;
document.getElementById("varNumber").innerHTML = varNumber;
document.getElementByID("varNumber").value = varNumber;
function addToVariable() {
varNumber= varNumber+ 1 ;
document.getElementById("varNumber").innerHTML = varNumber;
}
</script>

Here are three client-side methods to save JavaScript variables across page refreshes and descriptions on how long they can persist data.
Saving a JavaScript variable with local storage
Saving a JS variable using local storage is easy and convenient with modern browsers.
var get = function (key) {
return window.localStorage ? window.localStorage[key] : null;
}
var put = function (key, value) {
if (window.localStorage) {
window.localStorage[key] = value;
}
}
To save and read an object instead of a simple variable:
localStorage.yourObject = JSON.stringify(obj);
obj = JSON.parse(localStorage.yourObject || "{}");
Persistence:
User agents may, if so configured by the user, automatically delete
stored data after a period of time.
For example, a user agent could be configured to treat third-party
local storage areas as session-only storage, deleting the data once
the user had closed all the browsing contexts that could access it.
This can restrict the ability of a site to track a user, as the site
would then only be able to track the user across multiple sessions
when he authenticates with the site itself (e.g. by making a purchase
or logging in to a service).
However, this also reduces the usefulness of the API as a long-term
storage mechanism. It can also put the user's data at risk, if the
user does not fully understand the implications of data expiration.
References:
http://dev.w3.org/html5/webstorage/
Persisting values in JavaScript object across browser refresh
How persistent is localStorage?
Saving a JavaScript variable with cookies
Saving a variable with cookies:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
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;
}
Persistence:
Session cookies - these are temporary and are erased when you close
your browser at the end of your session.
Persistent cookies - these remain on the client hard drive until they
are erased or expire.
This is ultimately user-dependent. They could be paranoid about
cookies and local storage, and set them to session-only or none at
all.
REF: Set cookie and get cookie with JavaScript
Saving a JavaScript variable with window.name
You could also use the window’s name window.name to store the information using a JavaScript session.
Persistence:
This only works as long as the same window/tab is used.
REF: http://www.thomasfrank.se/sessionvars.html

You can use localStorage on client side
<script>
localStorage.setItem("mykey",99); // set a variable
var varNumber = localStorage.getItem("mykey"); // retrieve variable
</script>

You could use AJAX to execute PHP, like:
<?php
session_start(); $r = array();
if(isset($_POST['holdNumber'])){ // assumes {holdNumber:numberHere} sent through AJAX
if(preg_match('/^\d+$/', $_POST['holdNumber']){
$r['heldNumber'] = $_SESSION['holdNumber'] = $_POST['holdNumber'];
}
else{
// holdNumber hack
}
}
elseif(isset($_POST['load'])){
if(+$_POST['load'] === 1){ // assumes sending {load:1} in AJAX
if(isset($_SESSION['holdNumber']){
$r['heldNumber'] = $_SESSION['holdNumber'];
}
else{
$r['heldNumber'] = $_SESSION['holdNumber'] = 0;
}
}
else{
// load hack
}
}
echo json_encode($r);
?>

Related

On reload of the application, localStorage data will clear or not?

I want to use some data in my entire application. I am using localStorage to store the data .I am using it in my application but here is my issue , on Reload my entire localStorage values are removed from browser. Can anyone please tell me, localStoage values are removed when user reloads the application? If yes suggest me any other solution to use the data in entire application.
Localstorage is stored in the system, reload application would not erase it.
There are two variables localStorage and sessionStorage .
The difference between two is that data in localStorage has no expiration while sessionStorage clears your data when the page session ends.It depends whatever variable you want to use as per your requirement.
So localStorage will not clear your data when your page is reloaded.
You can use Cookies for store data until the session clears. That way your data will not be cleared when the app reload every time.
Use below code to store data in cookies,
document.cookie = "sampleData=www.samplesite.com";
document.cookie = "sampleUser=user001";
use below code to retrieve data from cookies,
function getCookieData(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;
}
function getSampleSite() {
var _st = getCookieData("sampleData");
return (_st != null) ? _st : "";
}
function getUser() {
var _st = getCookieData("sampleUser");
return (_st != null) ? _st : "";
}
Check for window.localStorage.clear() in your file and see if it is getting called on reload, as thats the only way to clear our localStorage and you might be hitting on it accidentally.
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.
so Ideally it should not clear the values of localStorage unlee you have manually triggered something to clear that (check for any method which is clearing it and triggered on page reload) if all looks good then there are next cases like exceptions:
Exceptions
SecurityError
The request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). For example, the user may have their browser configured to deny permission to persist data for the specified origin.
Reference : https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Appending a query string to the url on refresh using javascript

I am trying to read a label and append its value as a query string once the user hits the refresh button on their browser. The code I have so far is:
function AppendQueryString() {
var currUrl = document.location;
var trackingNbr = $("#lblTrackingNbr").text();
if (window.location.href.indexOf("?TrackingNumber=") <= 0 && trackingNbr !== null) {
document.location = currUrl + "?TrackingNumber="+ trackingNbr;
}
}
window.onbeforeunload = AppendQueryString();
The problem is, the trackingNbr variable is always null even though the label has the value before I hit refresh. What am I doing wrong or is there a better way of doing this ?
SessionStorage would be a good solution, with something like this:
sessionStorage.setItem("trackingNbr", trackingNbr);
When the refresh button is clicked, you can pull this value back from session storage easily:
var trackingNbr = sessionStorage.getItem("trackingNbr");
Security: Because this is session storage rather than local storage, the value will be cleared from the browser when the session ends. Note that only your domain can access whatever you put into either session or local storage. However, a knowledgeable end user can read the value by using developer tools in any of the major browsers.

How to delete the javascript cookies when the session invalidates on its own?

I have declared a cookie in my code which is created after specific function gets successful. I manipulate the cookie based on the method success or failure. Below is the code that I have used to create the cookie,
setCounterOfSuccess : function (c_name,value,days){
var expires='';
if (days){
var date=new Date();
date.setTime( date.getTime() + (days*24*60*60*1000) );
expires='; expires=' + date.toGMTString();
}
document.cookie= c_name + '=' + value + expires + '; path=/';
},
getCounterOfSuccess : function(c_name){
var nameEQ = c_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;
},
deleteCounterOfSuccess : function (name){
this.setCounterOfSuccess (name,'',-1);
},
I want these to be session cookies. So while setting the value I am setting them as below, I am passing ‘ ’ as last parameter to set them as session cookies.
I assume they will expire when the browser will be closed.
this.setCounterOfSuccess ("counterOfSuccess", Counter, '');
I am also deleting the cookie when I hit the logout button from the website. It looks like below,
logout: function()
{
this.deleteCounterOfSuccess ("counterOfSuccess");
}
So I am handling 2 ways of my how my cookies should get deleted. Now the problem is when I leave my website logged in for some time, it automatically logs out after a certain time period as expected. Which means that the session gets terminated or invalidated on its own. Now in this case if the browser is not closed and if I login again, the cookie is still there. And I don’t want that to happen. I want to have new cookie created at every session so that I can track the session related activities in the same.
Can anyone please advise how can I achieve this? How can I delete this cookie when the session terminates on its own after leaving it alone for a long time?
Thanks a lot.

load an ad (div) just once on first load

I wanted to know how can I have a div that has an ad to load or become visible ONLY the first time you load the page but hide it every time the page is refreshed?
I only have the code to load the div with Jquery but don't know how to hide it after refreshing the page:
$(document).ready(function() {
$(".referralProgram").fadeIn("slow");
});
Use a cookie:
$(document).ready(function() {
if (!readCookie("adSeen")) {
$(".referralProgram").fadeIn("slow");
createCookie("adSeen", "1", 1000);
}
});
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
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;
}
Cookie functions from quirksmode.org.
Edit: Since so many are discussing how to deal with this if cookies are disabled, it should be pointed out that server session implementations rely on either a cookie, or a session identifier in the url. At best, you could only prevent displaying the ad for the same user as long as the session identifier is in the url. Returning to the home page sans session id would re-display the ad. Additionally, a careless implementation (and even some careful implementations) could result in false positives for other users if a user shares a url. localStorage solutions won't work with cookies disabled in most, if not all, browsers.
You'll need a way to keep track of when an ad has been displayed to the user. Set a cookie when the ad is created and check for it before displaying again?
You can use client side persistent storage to flag the user has already seen this. Here are 3 options:
1) Cookies - Set a cookie on the visiting users machine.
2) HTML5 Storage - You can store the flag in browser (HTML5 Only) storage.
3) Server Session - If you are using middleware (PHP, ASP.NET, Java, etc.) you can track via a session variable (this is an abstraction of a cookie and is only as persistent as you create it to be).
I am not sure what your server side implementation is like, but if you are worried about cookies being turned off you could handle this on the server side using session state.

Accessing cookies, hopefully in JavaScript

I am working on a Firefox add-on that will allow users (all of whom are part of a specific group; this add-on is very limited in audience scope) to see the status of their authentication cookie from the status bar. We all have to authenticate to access work-related sites, but we get no warning when the cookie expires, so this causes annoying and sometimes drastic interrupts in work flow. Eventually, this add on will allow us to submit our credentials from the status bar without having to go to do any reloads or redirects, but for now, I just want to see it show the status.
I have been looking at the Mozilla developer pages at nsICookie, nsICookie2, nsICookieManager, etc, and it doesn't make very clear sense how any of it fits into JavaScript or XUL or anything else.
Ideally, I'd just like a way for the JavaScript to go outside of the document and get the cookie string for a domain I specify. If I could do that, it would allow the code to possibly be ported over to other browsers (Safari and Chrome, in particular). But if this must be browser specific, then I would at least like to know the method for checking if the cookie exists in Firefox without any bells and whistles of setting or removing.
Simply put, I want a way to say:
if (cookieExists("sample.com", CookieName)) {
alert("You're signed in!");
} else {
alert('Go sign in, you fool!');
}
What is the easiest/most portable way of doing this (browser-side, of course)?
I have been looking at the Mozilla developer pages at nsICookie, nsICookie2, nsICookieManager, etc, and it doesn't make very clear sense how any of it fits into javascript or XUL or anything else.
access to all cookies from Firefox extension is possible and uses the nsICookieManager and nsICookie interfaces. From javascript code in your extension, you access the cookie manager with
var cookieManager = Components.classes["#mozilla.org/cookiemanager;1"].getService(Components.interfaces.nsICookieManager);
and than you can iterate through all stored cookies
var enum = cookieManager.enumerator;
while (enum.hasMoreElements()){
var cookie = enum.getNext();
if (cookie instanceof Components.interfaces.nsICookie){
// commands
}
}
now, when having reference to cookie object you can check its properties
cookie.host
cookie.name
cookie.value
...
defined in nsICookie interface. This code is Firefox specific and can be run as a browser extension or signed script. Hope my explanation helped a bit.
Below I present some links on using JS XPCOM interfaces in extensions:
JS XPCOM
Using cookies
you can use jquery plugin for cookie handling
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
or simply through javascript :
http://www.quirksmode.org/js/cookies.html
Here's a nice tutorial for working with cookies in javascript. Using the functions from that tutorial, you could probably do something like this:
if readCookie(yourCookieName != "") {
alert("You're signed in!");
else {
alert("Go sign in, you fool!");
}
Here are the cookie functions:
function readCookie(name) {
var ca = document.cookie.split(';');
var nameEQ = name + "=";
for(var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return "";
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}

Categories

Resources