How do you make a variable that is changing every reload? - javascript

The variable I'm talking about is like page views. I want it so the variable doesn't start at 1 every time. So every time you reload it, the pageviews variable adds by 1. All I have is:
HTML:
<div id='pageviews'></div>
Javascript:
var pageviews;
pageviews += 1;
document.getElementById('pageviews').innerHTML = pageviews;
I didn't use CSS because that was optional.

You can use sessionStorage or localStorage deppending on the behaviour expected.
$(document).ready(function() {
var currentUpdateCount = sessionStorage.getItem("updateCount") ? sessionStorage.getItem("updateCount") : 1;
sessionStorage.setItem("updateCount", currentValues + 1);
});
The sessionStorage is alive only in the time that the current session is open in the browser.
The localStorage persist after you close and open the browser again.
You can know more about the html5 storage system here

Use localStorage to store the count as :
var count = 0;
localStorage.setItem('count', count);
and use var count = localStorage.getItem('count'); to retrieve the value (remember localstorage stores as string and not as integer so you can't directly use it as an integer.
OR
Use Cookies, set a cookie by setcookie(), although you will have to set some Expiry date to it.
EDIT : This is exactly what to want to achieve. Hope it helps.

You will need to send an ajax request to the server and store it in a database.
If you only want to test your code, you can use localStorage for now and then modify the code to send the ajax request later on.

Related

How to save html user input as javascript variable on next page?

I want to save user input as a Javascript variable so I can use it on other pages of my site. How can I do that? Now the variable will be deleted if I go to the next page and I get the error "Uncaught ReferenceError: userInput is not defined"
Here is my code:
function test(){
const userInput = document.getElementById("naam").value;
window.location.href = "interactie1.html";
console.log(userInput);
}
document.getElementById("js--terminal--text").innerHTML = "";
typeText = (textToBeTyped) =>{
if(textToBeTyped != ""){
document.getElementById("js--terminal--text").innerHTML += textToBeTyped[0];
textToBeTyped.splice(0,1);
setTimeout(() => {
typeText(textToBeTyped);
},100);
}
}
typeText(Array.from("Hello this is "))
typeText(userInput);
<input class="naam__aanwezigheid__form" type="text" id="naam" placeholder="Type je naam" required>
<button onclick="test()">Submit</button>
Since you are changing the page, the script is unloaded, therefore you can't access these variables.
Maybe you can try this : Session storage
Or make sure you've loaded the script in the first place to use the variables.
If you are using tools like React, they have the concept of states, that will allow you to hold the variable in memory, while you change the URL ( React is a single page application though ).
Otherwise, you will either need to use cookies, or have a server to hold those values for you while you change pages.
Use localstorage for save your values.
localStorage.setItem("key", "your value");
Then get saved values in next page.
let your_value = localStorage.getItem("key");
The userInput will be empty since you're loading another page.
You'd be needing a storage, you can access the browsers storage section with:
window.localStorage.setItem('userData ', userInput);
It's stores it as a key value pair.
userData is key for retrieval.
userInput is the value that is returned.
Hence, on loading the new page you can retrieve it using:
window.localStorage.getItem('userData');
Feel free to read more on localStorage in js.
you may want to use the JavaScript Session Storage API. using URL Parameters should do the trick too.

Counter Variable saved after web page refresh

I'm trying to get the counter variable saved when the page refreshes. For example, if the counter is at 5,000 then after refresh the counter will start back up at 5,000 and keeps saving so it doesn't start at the default value.
var count = 309000000;
function tick(){
count += Math.round(Math.random()*3);
$('#test').text(count.toLocaleString());
count;
setTimeout(tick,Math.round(1000+Math.random()*3000));
}
tick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p id="test"></p>
This code I have sets the default variable to 309,000,000 but everytime I refresh the page the value doesn't save and go back to the default. Please assist on where to start with this. I've looked at local storage and cookies but don't quite understand it.
You can save the variable in sessionStorage using sessionStorage.setItem('key','value')
Docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
example: https://codepen.io/simranz/pen/GBXpPw
Another option is to use localStorage
Docs at: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

Keeping a user-defined JScript variable after reload?

In my HTML document, a button is displayed, and it's onclick event is to alert the variable countervar. Another button can be used to bring countervar up using countervar++. Countervar is never defined in the JScript document, because I want countervar to stay how it was last defined by a user. Like I expected, countervar was nil after each reload. Saving browser cookies also would not work, because the same variable has to be displayed to each user who views the document. I'm looking into "global variables" for an answer, but no luck. Help?
As suggested in the comments, you can use localStorage to achieve part of what you want:
var counter;
// save to local storage
window.localStorage.setItem("counter", counter);
// you can call this whenever you make changes to the counter variable
// load from local storage
// call it when the page loads
if( window.localStorage.getItem("counter") === null){
counter = 0;
}
else{
counter = parseInt(localStorage.getItem("counter"));
}
This will allow you to save the variable for one user. If you want to share it between users, it can't be done just using client side scripting. You'll have to have some sort of server storage/database.

Jquery / Javascript - get list of request URLs for that session like in browser console

I need to be able to retrieve the list of request URLs that are displayed in the browser console, i.e: GET http://mydomain.com/index.php?p=1&curr=GBP&cat=Food. 200. Users can click around my app and apply different filters and scrolls through pages and I need some way of tracking this so that I always know what data has already been loaded for that users session.
I had thought about using PHPs $_SERVER['REQUEST_URI'] and saving them in a session but then I don't know how I would access this session from my JQuery as its JQuery that constructs the URLs.
Has anyone any idea how I can access this data from the console? Is this possible? If not can anyone suggest a workaround?
The PHP / JQuery mess I have so far:
<?php
session_start();
//keep track of requests.
if (!isset($_SESSION['requests'])) {
$_SESSION['requests'] = array();
} else {
if (!in_array( $_SERVER['REQUEST_URI'], $_SESSION['requests'])) {
$_SESSION['requests'][] = $_SERVER['REQUEST_URI'];
}
}
$requests = json_encode($_SESSION['requests']);
print_r($_SESSION['requests']);
print_r($requests); //these both have values
?>
//further down the page is the javascript
$('.filter a').click(function(e) {
var $this = $(this);
var $optionSet = $this.parents('.option-set');
var group = $optionSet.attr('data-filter-group');
filters[ group ] = $this.attr('data-filter-value');
//***more code for filtering etc******/
var paginate_url = $('.paginate a').attr('href');
//THIS IS PART I CANNOT GET WORKING
var visited_urls= <?=$requests?>;
//console.log($.parseJSON(visited_urls));
console.log(visited_urls); //is always empty
var pageno = ''; //somehow check to see if the URL that has been clicked exists int he requests array, if so get the page number and increment.
var next_url = UpdateQueryString(paginate_url, pageno, group, encodeURIComponent(filter_qry));
I'm not completely sure what you're trying to do but I think you can skip the PHP and just use JavaScript and sessionStorage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage or localStorage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage (depending on how persistent you want the data to be)
For example if I want to listen for all clicks on 'a' tags and track whether those hrefs have been visited (and how many times)
$(document).ready(function() {
// store an empty object in session storage when the page loads
sessionStorage.visited = JSON.stringify({});
});
$('a').on('click', function() {
var storage = JSON.parse(sessionStorage.visited),
href = $(this).attr('href');
// when we get a click check to see if this has been clicked before
if (!storage[href]) {
// if not save it and set the count to 1
storage[href] = 1;
} else {
// otherwise increment the count
storage[href]++;
}
sessionStorage.visited = JSON.stringify(storage);
});
If you want to save the urls from your ajax calls the same principle applies but listen for the ajaxSuccess event and store the url from the request in the callback: http://api.jquery.com/ajaxSuccess/
This is my suggestion:
PHP + Javascript Implementation:
In PHP, use $_GET['curr'] and $_GET['cat'] to retrieve the arguements from the URL.
Use $_SESSION['curr'] = $_GET['curr']; to save them per the session.
On your Javascript/jQuery use var curr = "<?php echo $_SESSION['curr']; ?>" to make the PHP session variables available to your Javascript.
Basically the key to have a good PHP/Javascript persistent memory is that you can set PHP content into a Javascript variable by using:
var x = <?php echo '123';?>;
console.log(x); //output '123' to Javascript console
If you need to have a list of all visited urls, you can save them in a PHP array and transfer it to Javascript as well.
On PHP side:
if (!isset($_SESSION['visited'])) $_SESSION['visited'] = array();//initialize the array if doesn't exist
if (!inarray( $_SERVER['REQUEST_URI'], $_SESSION['visited']) { //check if current URL is not in array
$_SESSION['visited'][] = $_SERVER['REQUEST_URI'];//push it to the array
}
On Client side:
//this will convert the PHP array to a Javascript array using json_encode
var visited_urls= <?php echo json_encode($_SESSION['visited']); ?>;
Don't forget to use session_start() on every page you need the session variables.
Javascript Only Implementation:
Use localStorage and keep everything on the client side.
EDIT: Note that localStorage is only supported in IE8 and up, so if versions prior to IE8 must be supported, you will need to use Cookies instead of localStorage.
$(document).ready(function() {
var urls = JSON.parse(localStorage["visited"]) || [];//get the visited urls from local storage or initialize the array
if (urls.indexOf(document.URL) == -1) {//if current url does not exist in the array
urls.push(document.URL);//add it to the array
localStorage["visited"] = JSON.stringify(urls);//save a stringifyed version of the array to local storage
}
});
Hope this helps!
It's unclear what you want to achieve with this feature. You state:
Users can click around my app and apply different filters and scrolls through pages and I need some way of tracking this so that I always know what data has already been loaded for that users session.
What do you want to achieve with this, why isn't the browser's cache enough for you?
My idea for a solution would be to sync server session array with an object inside the Browser via some sort of WebSocket (http://en.wikipedia.org/wiki/WebSocket).
UPDATE2:
It is possible to use localStorage as cache storage as Abel Melquiades Callejo suggests and then read from it bypassing HTTP requests. I would choose what content to save to that cache differently, no server involved:
add a custom attribute data-* to every HTML element you want cached (http://html5doctor.com/html5-custom-data-attributes/);
make a querySelectorAll (https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll) for all HTML elements with that attribute;
storing and retrieving documents from localStorage should be easy now, you need a convention for naming files for easy finding;
storing images implies doing a base64 transformation which increases the size of the data by 34% (image with 64kb will take 86kb in localStorage).
you need a way to find when data in localStorage is obsolete and you need to make requests to the server (perhaps another data-age attribute to specify when should it expire).
However, this localStorage solution is limited to a small amount of data, see this issue https://github.com/RemoteStorage/remoteStorage.js/issues/144. So, although I now see that what you are asking is possible, because of this size limitation to localStorage, I strongly recommend the solutions in my UPDATE1, below.
UPDATE1: The point is that caching mechanisms are incredibly complex. A better alternative would be to use the default browser caching mechanisms:
1. HTML5 cache manifest
Go offline with application cache
http://html5doctor.com/go-offline-with-application-cache/
LET’S TAKE THIS OFFLINE http://diveintohtml5.info/offline.html
Using the application cache
https://developer.mozilla.org/en/docs/HTML/Using_the_application_cache
A Beginner's Guide to Using the Application Cache http://www.html5rocks.com/en/tutorials/appcache/beginner/
2. Server's response headers to HTTP requests
Optimize caching - Leverage browser caching
https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
HTTP Caching FAQ https://developer.mozilla.org/en/docs/HTTP_Caching_FAQ

Categories

Resources