Counter variable does not persist when loading a new page - javascript

I want to use counter variable in javascript like static variable with timer. counter must decrease by 1 on every second. I m working on online exam. on answering a question new question comes on the same page. my problem starts when counter variable is initialized with new question(means new page). counter variable does not persists on new page...suggest any solution
<script language="JavaScript">
function ExamTimer()
{
if ( typeof ExamTimer.counter == 'undefined' )
{
ExamTimer.counter = 30000; // 30 min
}
else
{
ExamTimer.counter = ExamTimer.counter-1;
if(ExamTimer.counter<=0)
{
alert("exam finish");
}
setTimeout(ExamTimer, 1000);
}
window.onload=ExamTimer;
</script>

Javascript variables are not meant to outlive the current page load. The browser's Javascript engine executes the code on every page load (though most browsers cache the complied code), so client-side variables are lost whenever the page reloads.
There are several common methods to pass values from one page to another:
DOM storage
Cookies
Server-side variables via a GET or POST request
Whatever method you select, remember it needs to be adequately resilient to unwanted manipulation by the user.

Using ajax pass value from one to another page. use session to hold last remainTime thai is passed to next page
<script language="JavaScript">
function ExamTimer()
{
if ( typeof ExamTimer.counter == 'undefined' )
{
ExamTimer.counter = <cfoutput>#session.RemainTime#</cfoutput>;
}
else
{
ExamTimer.counter = ExamTimer.counter-1;
$.get('linktosend.cfm',{counter:ExamTimer.counter},function(responseText)
{
// value of ExamTimer.counter send to linktosend.cfm and store in session.RemainTime
});
if(ExamTimer.counter<=0)
{
alert("exam finish");
}
setTimeout(ExamTimer, 1000);
}
window.onload=ExamTimer;
</script>

Related

Why does my local storage function does not update variable?

So I was trying to create an incremental game or clicker game or idle game. And everything else is fine, but when it comes to the save and load function it's broken. So my load function works wonderfully, but the problem is that my save function won't save the updated variable, instead, it saves the not updated variable which basically makes the saving and loading pointless.
Code:
function saving() {
localStorage.setItem('save',JSON.stringify(save));
alert("save correctly!");
}
function load() {
var savegame = JSON.parse(localStorage.getItem("save"));
if (typeof savegame.Cookies !== "undefined") cookies = savegame.Cookies;
if (typeof savegame.Cursors !== "undefined") cursors = savegame.Cursors;
if (typeof savegame.Farms !== "undefined") farms = savegame.Farms;
console.log("cookies : ", cookies);
console.log('farms :', farms);
console.log('cursors :', cursors);
}
and I defined the variable "save" as the following.
var save = {
Cookies: cookies,
Cursors: cursors,
Farms: farms
}
and the cookies, cursors, and farms, variables are all set to zero.
After I increment the value in my game, however, the save variable is still using the not incremented variable.
I want it to save the variable like this: 2000 cookies, 30 cursors, 7 farms, instead of all 0.
I am fairly new to js and I've been trying this for the last two days now.
Maybe it's just some ignorant and careless mistake, someone please point it out.
You need to call saving method on every change of the variable save.

Using Localstorage to store and retrieve javascript variables from one html page to another (DOM)

I have one html page 1.html and i want to get some text content and store it to a js.js file using jquery to get the text by id.
This code only works in 1.html page, where the text I want to copy from is but not in 2.html file.
Here is my code. Note that it works if I store text inside localstorage setter second parameter.
$( document ).ready(function() {
var c1Title= $('#r1c1Title').text();
//changing c1Title to any String content like "test" will work
localStorage.setItem("t1",c1Title);
var result = localStorage.getItem("t1");
$("#title1").html(result);
alert(result);
});
Here is the complete demo I am working on Github:
You need to use either localStorage or cookies.
With localStorage
On the first page, use the following code:
localStorage.setItem("variableName", "variableContent")
That sets a localStorage variable of variableName for the domain, with the content variableContent. You can change these names and values to whatever you want, they are just used as an example
On the second page, get the value using the following code:
localStorage.getItem("variableName")
That will return the value stored in variableName, which is variableContent.
Notes
There is a 5MB limit on the amount of data you can store in localStorage.
You can remove items using localStorage.removeItem("variableName").
Depending on where you are, you may need to take a look at the cookie policy (this effects all forms of websites storing data on a computer, not just cookies). This is important, as otherwise using any of these solutions may be illegal.
If you only want to store data until the user closes their browser, you can use sessionStorage instead (just change localStorage to sessionStorage in all instances of your code)
If you want to be able to use the variable value on the server as well, use cookies instead - check out cookies on MDN
For more information on localStorage, check out this article on MDN, or this one on W3Schools
Please try to use this code. It's better to use local storage.
Here you need to make sure that you are setting this local storage
value in parent html page or parent js file.
create local storage
localStorage.setItem("{itemlable}", {itemvalue});
localStorage.setItem("variable1", $('#r1c1Title').text());
localStorage.setItem("variable2", $('#r1c2Title').text());
Get local storage value
localStorage.getItem("{itemlable}")
alert(localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
For more information follow this link https://www.w3schools.com/html/html5_webstorage.asp
If you wanted to store in div then follow this code.
Html Code
<div class="div_data"></div>
Js code:
$(document).ready(function () {
localStorage.setItem("variable1", "Value 1");
localStorage.setItem("variable2", "Value 2");
$(".div_data").html(' First variable ::: '+localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
});
Hope this helps.
You can use local storage as mentioned in above comments. Please find below how to write in javascript.
Local Storage Pros and Cons
Pros:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity.
5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain.
This gives you considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
Cons:
It works on same-origin policy. So, data stored will only be available on the same origin.
// Store value in local storage
localStorage.setItem("c1Title", $('#r1c1Title').text());
// Retrieve value in local storage
localStorage.getItem("c1Title");
Your html div
<div id="output"></div>
Add Javascript Code
$('#output').html(localStorage.getItem("c1Title"));
Let me know if it not works
Create a common.js file and modified this and save.
Session = (function () {
var instance;
function init() {
var sessionIdKey = "UserLoggedIn";
return {
// Public methods and variables.
set: function (sessionData) {
window.localStorage.setItem(sessionIdKey, JSON.stringify(sessionData));
return true;
},
get: function () {
var result = null;
try {
result = JSON.parse(window.localStorage.getItem(sessionIdKey));
} catch (e) { }
return result;
}
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
}());
function isSessionActive() {
var session = Session.getInstance().get();
if (session != null) {
return true;
}
else {
return false;
}
}
function clearSession() {
window.localStorage.clear();
window.localStorage.removeItem("CampolUserLoggedIn");
window.location.assign("/Account/Login.aspx");
}
Insert like this.
$(function () {
if (!isSessionActive()) {
var obj = {};
obj.ID = 1;
obj.Name = "Neeraj Pathak";
obj.OrganizationID = 1;
obj.Email = "npathak56#gmail.com";
Session.getInstance().set(obj);
}
///clearSession();
});
get like this way
LoggedinUserDetails = Session.getInstance().get();

How to automatically reload a web page

I want my website page to reload once when it has already opened for the first time. I wrote this function in my javascript file for that...
var i;
$(document).ready(function(){
for ( i=0;i<1;i++){
if(i===0){
location.reload();
break;
}
}
});
But the page keeps reloading again and again as if the above function was a recursive one.
How do I do this?
P.S I'm doing it because of this issue.
<script type='text/javascript'>
(function() {
if( window.localStorage ) {
if( !localStorage.getItem('firstLoad') ) {
localStorage['firstLoad'] = true;
window.location.reload();
} else
localStorage.removeItem('firstLoad');
}
})();
</script>
Here is what's happening:
The page loads for the first time, jQuery calls any handlers on the document.ready event
The page reloads
The document.ready call is made again
repeat
Out of curiosity, why would you want to do that? And why do you have a for loop that will run for one iteration?
Also, to answer your question as far as I know the only way to make sure the page doesn't reload is use a cookie that lasts for about 5 seconds. Then, on document.ready check for that cookie and if it exists then don't reload.
You must either set a cookie (or use javascript's localStorage), or use xhr to retrieve a value held on a remote server.
If you want to use cookies, it's as simple as
document.cookie = "username=John Doe";
where the document.cookie is a query string of the form (x=y;a=b;n=z)
If you want the page to reload every time the user vists, be sure to unset the cookie once you've done any necessary processing when a page reload has been set.
$( window ).load(function() {
if (window.location.href.indexOf('reload')==-1) {
window.location.replace(window.location.href+'?reload');
}
});
Code is ok. But if the page is opened from another page with a link to an id (.../page.html#aa) the code only works with firefox. With other browsers reload the page without going to id. (Sorry for my english).
I found the solution with this code. It is assumed that the page is refreshed no earlier than one hour. Otherwise, add minutes to the oggindex variable.
<script>
var pagina = window.location.href;
var d = new Date();
var oggiindex = d.getMonth().toString()+'-'+d.getDate().toString()+'-'+d.getHours().toString();
if (localStorage.ieriindex != oggiindex)
{
localStorage.setItem("ieriindex", oggiindex);
window.location.replace(pagina);
}
</script>
Yours code executed each time $(document).ready(), so it's not surprise that your loop is infinity - each load finished as ready state.
If you give more detailed requirements we can solve it with no using window object as data holder. It's bad way but you can set it for test.
Window object stores variables not depend on reload because it's higher then document.
Let's try:
if( window.firstLoad == undefined ){
// yours code without any loop
// plus:
window.firstLoad = false;
}
You can make it with localStorage API.
Check this link also, it's giving more information about window object variables:
Storing a variable in the JavaScript 'window' object is a proper way to use that object?

Continual counter regardless of page refresh

I have this piece of jQuery that currently increments a number by one every 5 seconds. The problem I have is that its client side, therefore it resets every time you refresh the page.
Instead I'd like the counter to continue even if you are away from the site and regardless of how many times you refresh the page, which is why I thought a server side script such as PHP would be better suited to my use case. If not please suggest otherwise.
I've setup a working fiddle of what I currently have with jQuery: http://jsfiddle.net/f354bzy5/
What would be the PHP to recreate this affect that include my requirements above?
Here's the Jquery I'm using:
//Counter
var counter = 22000000000;
$(".count").html(counter);
setInterval(function () {
$(".count").html(counter);
++counter;
}, 5000);
Check this DEMO
//Counter
var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object')
{
counter=parseInt(localStorage.getItem('counts'));
}
setInterval(function () {
$(".count").html(counter);
++counter;
localStorage.setItem('counts',counter);
}, 1000);
Highlight on localStorage
localStorage is an implementation of the Storage Interface. It stores
data with no expiration date, and gets cleared only through
JavaScript, or clearing the Browser Cache / Locally Stored Data -
unlike cookie expiry.
Can you store counter in cookie.
document.cookie = counter.
so you can get last value from cookie, if user refresh the page.
It comes down to two simple choices for you. Just choose the right one which better fits your requirement:
Choose Cookie : If you want the server side to access the counter. Remember cookies are sent along with the requests by default.
Choose Local Storage : If you don't want to send the counter along with requests every time, you are supposed to go for local storage.
You could do it with localStorage. Here's how I am doing it. You can tweak it as you need.
//detecting support for localStorage.
if (window.localStorage) {
//counterValue already exists in localStorage? Let's use that or set to zero.
var counterValue = localStorage.counterValue || 0;
setInterval(function() {
//increment the counter and store updated vale in localStorage as well.
localStorage.counterValue = ++counterValue;
//put it in your HTML if you might
$(".count").html(counterValue);
}, 5000);
}
How about using localStorage with some utility functions? Bear in mind that this is a client side solution and the item would be wiped off when the user deletes the browser cache/local data etc.
function isLocalStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
function setCounter(key, val) {
localStorage.setItem(key, val);
}
function getCounter(key) {
return parseInt(localStorage.getItem(key), 10);
}
(function() {
var key = "myCounter";
var counter = isLocalStorage() && getCounter(key) || 1;
var $placeholder = $(".count");
$placeholder.html(counter);
setInterval(function () {
counter++;
$placeholder.html(counter);
isLocalStorage() && setCounter(key, counter);
}, 2000);
}());
-- Demo --

Maintaining a Javascript variable between HTML pages to send to database?

I'm doing an experiment for university that involves timing how long participants take to read a simple webpage. Because of the nature of the experiment, I can't tell them I'm timing them before they visit the page, so on the following page I need to tell them that they were being timed and then offer an option to opt out if they object to their data being passed on to a database using a Python CGI script.
At the top of the first page I have this:
<script type="text/javascript" src="timing.js">
</script>
And at the bottom I have a link to take them to the next page, but also to stop the timer:
Click here when you are ready to proceed.
<button onclick="window.location = 'timer2.html'; stopTime()">Click Here</button>
...and in the .js file, I have the following:
var sec = 0;
function takeTime()
{
setInterval(function(){sec += 1},1000);
}
myTime = takeTime();
function stopTime()
{
clearInterval(myTime);
}
function showTime()
{
alert("Time is " + sec + " seconds.");
}
When I click the link to go the second page, the "sec" variable just resets to 0. If I take the declaration out of the .js file and put it in a separate script tag before the one that refers to the .js file in the first HTML page, the second HTML page doesn't recognise the variable "sec" at all. How can I store the time so that I can then either send it to a database or get rid of it from the second HTML page?
One way is to use the query string.
<button onclick="window.location = 'timer2.html?time=' + sec">Click Here</button>
They will be sent to eg timer2.html?time=252 if it took 252 seconds. Then use How can I get query string values in JavaScript? to get this value on timer2.html.
Javascript variables do not maintain their state from one page load to the next, so you will need another way to store that information. Another method besides passing it through the query string is HTML5 Local Storage. Using Local Storage, you can store values in the browser that are retrievable from one page load to the next, within the same domain.
For example, your first page:
var sec = 0;
localStorage.time = 0;
function takeTime()
{
setInterval(function(){sec += 1},1000);
}
myTime = takeTime();
function stopTime()
{
clearInterval(myTime);
localStorage.time = sec;
}
function showTime()
{
alert("Time is " + sec + " seconds.");
}
And somewhere in timer2.html:
var sec = localStorage.time;

Categories

Resources