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

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;

Related

setInterval change Interval

Hello I am new in javascript, I am making chrome extension, this extension contains the setInterval command, I want to change the time with javascript to the textbox I have added to a website. This change should remain when I refresh the page, how can I do this.
My content script start document_end
var Refresh = setInterval(clickerStart,4000)
function clickerStart(){
var selection1 = document.querySelector("#\\30 ") !== null;
if (selection1) {
location.reload();
} else {
console.log("Islem Bulundu.");
};
}
//textbox
var Interval = document.createElement("INPUT");
Interval.setAttribute("type", "text");
Interval.setAttribute("value", " ");
document.body.appendChild(Interval);
If you are not handling with sensitive data, which I think it is the case, you can use localStorage or cookies to store and reuse data (the interval time) until the user returns to the page (after refreshing it or reopening it).
Here's an explanation on how to set cookies:
https://www.w3schools.com/js/js_cookies.asp

Auto refresh specific div and load image with jquery/ajax

I have an internet radio station and I need a script that will display a picture of the current song in a particular dvi with an id. The image is automatically uploaded via ftp to the server each time the song changes..
HTML:
<div id="auto"></div>
JS:
$ (document).ready(function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
});
function refresh() {
setTimeout (function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
}, 1000);
}
I tried this, but all I get is that the image is loaded, but in case of a change, I have to manually refresh the whole page again..
I'll point out multiple things here.
I think your code is just fine if you are going for the setTimeout recursive calls instead of one setInterval action to repeat it.
File Caching
your problem is probably the browser's cache since you are using the same image name and directory all the time. browsers compare the file name and directory and to decide to load it from its cache or else it will request it from the server. there are different tricks you can do to reload the image from the server in this particular case.
Use different file names/directories for the songs loaded dynamically
Use a randomized GET query (e.g. image.png?v=current timestamp)
Your method for switching
you are replacing the file with FTP, I wouldn't recommend that. maybe you should have all your albums and thumbnails uploaded to the server and use a different dynamic switching for efficiency and less error proneness and will help you achieve method #1 in the previous section better.
Loading with constant refresh
I would like to highlight that if you are using nodeJs or nginx servers - which are event based - you can achieve the same functionality with much less traffic. you don't need a refresh method since those servers can actually send data on specific events to the browser telling it to load a specific resource at that time. no constant refresh is required for this.
You consider your options, I tried to be as comprehensive as I could
At the top level, browser cache the image based on its absolute URL. You may add extra query to the url to trick browser that is another new image. In this case, new URL of artist.png will be artist.png?timestamp=123
Check this out for the refresh():
function refresh() {
setTimeout (function() {
var timestamp = new Date().getTime();
// reassign the url to be like artwork.png?timestamp=456784512 based on timestmap
$('#auto').html('<img src="artwork.png?timestamp='+ timestamp +'"></img>');
refresh();
}, 1000);
}
You may assign id attribute to the image and change its src url
html
<img id="myArtworkId" src="artwork.png"/>
js in the refresh method
$('#myArtworkId').attr('src', 'artwork.png?timestamp=' + new Date().getTime());
You can use window.setInterval() to call a method every x seconds and clearInterval() to stop calling that method. View this answer for more information on this.
// Array containing src for demo
$srcs = ['https://www.petmd.com/sites/default/files/Acute-Dog-Diarrhea-47066074.jpg',
'https://www.catster.com/wp-content/uploads/2018/05/Sad-cat-black-and-white-looking-out-the-window.jpg',
'https://img.buzzfeed.com/buzzfeed-static/static/2017-05/17/13/asset/buzzfeed-prod-fastlane-03/sub-buzz-25320-1495040572-8.jpg?downsize=700:*&output-format=auto&output-quality=auto'
]
$i = 0;
$(document).ready(function() {
$('#auto').html('<img src="https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"></img>');
// call method after every 2 seconds
window.setInterval(function() {
refresh();
}, 2000);
// To stop the calling of refresh method uncomment the line below
//clearInterval()
});
function refresh() {
$('#auto').html('<img src="' + $srcs[$i++] + '"></img>');
// Handling of index out of bound exception
if ($srcs.length == $i) {
$i = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="auto"></div>

Refresh just home page

I am currently designing a system which includes a homepage that show the person who logs in only the work they have to do. I have been asked to set up this homepage to refresh every 3 minutes which I have done using this code:
function startTimer() {
var now = new Date();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var secTime = minutes*60*seconds;
if(secTime % (3*60) == 0){
var refreshTime = 3*60*1000;
} else {
var refreshTime = (secTime % (3*60)) * 1000;
}
setTimeout('refresh()', refreshTime);}
function refresh() {
window.location.href = 'myURL';
}
startTimer();
The problem I currently have is that when I navigate away from this page, but still in the system, it keeps returning me to homepage and I lose what I am working on.
Is there a way that I can keep refreshing homepage for those who haven't moved away from it and stop it when someone does?
I am very new to Javascript so please be patient if I ask a lot of question.
Thank you in advance for any help given.
I assume you are using a shared javascript file on all pages of the site which is why the timer will keep running on every page. You could make sure that the timer only runs on the homepage by checking the page url and wrap your startTimer function inside this check:
if (document.location.href == "http://www.yourhomepage.com"){
startTimer();
}
Replace http://www.yourhomepage.com with whatever url your homepage is on. This will only work if your pages are separate html files. If you are using a hashbang method whereby the document doesn't change, this will not work.
You can use Ajax to refresh the work log part of the page instead of refreshing the whole page.
When you refresh your page, your code redirect you to your home page because of window.location.href = 'myURL';. The location change, and it redirect you everytime to 'myURL'.
You would like to refresh only a part of your page. You have to send a XMLHttpRequest or Ajax request ( you load a page into your current page without reloading your current page ). https://developer.mozilla.org/fr/docs/XMLHttpRequest
When you get the page loaded, you insert the text loaded into the page.
Then, call the function which send request, every "refreshTime" like that
function sendAjax(){
// ... ajax request
// refreshTime = 3 * 60 * 1000;
setTimeout( sendAjax, refreshTime );
}
sendAjax();
Don't use quote arround the function name in setTimout. setTimemout need a function to call (not his name but his value) and time parameters.

Trying to refresh ping information from a Minecraft server - possible or not?

I am making a (kinda) dashboard for managing Minecraft servers. What I am currently trying to do is printing how many players are online (across all servers) AND refreshing the value every 3 seconds.
What works - showing the total amount of players - once only; refreshing (with jQuery) the corresponsing div works too (debug-tested).
What doesn't work - when refreshing (with jQuery) and printing the value of a PHP function, it doesn't refresh the function itself (its just printing the same thing over and over again).
Note: I do not get any errors from the client and server consoles.
Here is the code:
PHP - getting the amount of players across servers:
function getPlayersTotal() {
$total = 0;
foreach (getServers() as $serverInfo) {
if (isOnline($serverInfo)) {
$ping = json_decode(file_get_contents('http://api.minetools.eu/ping/' . $serverInfo), true);
$total += intval($ping['players']['online']);
}
}
return $total;
}
JS - refreshing the - located in HEAD.
<script>
$(document).ready(
function() {
setInterval(function() {
var players = <?php print "" . getPlayersTotal() ?>;
$('#playersPLZ').text(
"" + players);
}, 3000);
});
</script>
Can anyone explain to me if (1.) is it possible to refresh the values - somehow - of the PHP function, and (2.) how to do so?
Regards.
This is a job for Ajax. Here's what's happening now: your PHP code is outputting the number of players directly into the JavaScript that's sent to the browser. If the number of players is 50, then all the browser sees is this:
<script>
$(document).ready(
function() {
setInterval(function() {
var players = 50;
$('#playersPLZ').text(
"" + players);
}, 3000);
});
</script>
So the same function, with the number 50, is run every three seconds. The browser doesn't know anything about your PHP, it just sees the number 50. For all the browser knows, it's the same as if the number 50 were hardcoded in.
What you need to do is to send a request back to the server every 3 seconds asking for the new number, since your server is where the PHP code is run.
You need to create a new PHP file. I'll call it num-players.php. That file should output the number of players. You could do something along these lines:
<?php
// You will need to require the file containing your getPlayersTotal() function
echo getPlayersTotal();
?>
Then, your JavaScript can be something like this:
<script>
$(document).ready(function() {
setInterval(function() {
$.get("num-players.php", function(players) {
$("#playersPLZ").text(players);
});
}, 3000);
});
</script>
This will send a request back to your server every 3 seconds, asking for the new number. The code in num-players.php will return that number, and when the request completes, your element will be updated with the number.

Counter variable does not persist when loading a new page

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>

Categories

Resources