Variable Resets to 0 every refresh - javascript

I'm trying to make a code which lets me show how much a certain part of my website has been views.
My problem is, when I fresh refresh, it goes back to zero, instead of 2. I hope you can help me out. I want the code to run forever, or as long as I want it to, and it will just add a 1 to what it has been, even if it was yesterday. Here's the sample of the code.
<script type="text/javascript">
var bannerViews = 0;
function addViews (){
bannerViews = bannerViews + 1;
}
addViews();
</script>
<p>This banner has been viewed <script type="text/javascript">document.write(bannerViews);</script> timesĀ </p>
Hope you can help me out.

It is because every time you refresh your page, your code reinitializes. In-order to persist the data, you need to store it somewhere. Either in a cookie or a localstorage.
If you go ahead with the localstorage, here's how you do it.
var bannerViewCount = localStorage.getItem('bannerViews');
if(!bannerViewCount) {
bannerViewCount = 0;
}
function addViews() {
localStorage.setItem('bannerViews', ++bannerViewCount);
document.body.innerHTML = 'Banner view count is :' + bannerViewCount;
}
addViews();
Demo (click on Run on the top bar multiple times and see it incrementing)
Here, what am doing is first, fetching the banners view count. If I don't get it, I initialize it with zero.
Later, I on addViews() call, I increment the bannerViewCount by one and store it to the localStorage. That's it.
Note that the data is stored in your local storage, so if you are expecting that the count should be visible to other users too, you need to store it in a database or a text file and later parse it.
If you want to store it on the cloud, so that you can share the count across the visitors, you can do something like this.
function addViews() {
$.get('//jsonbin.io/b/5974382ca489d40388582791/latest', function(data) {
var bannerViewCount = data.bannerviews;
$.ajax({
url: '//jsonbin.io/b/update/5974382ca489d40388582791',
type: 'post',
dataType: 'json',
data: {
snippet: JSON.stringify({
bannerviews: ++data.bannerviews
})
},
success: function(fetch) {
var data = fetch.data;
document.body.innerHTML = 'Banner view count is : ' + JSON.parse(data).bannerviews;
}
});
});
}
addViews();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on "Run Code Snippet" button and see the counter incrementing. Go to any other browser and the count will persist as expected. Note that the data stored here can be manipulated as there is no authentication in place. So avoid it if you want the count to be precise and legit.

It goes back to 0 because the variable bannerViews is reinitialised to 0 on every page load.
You will need to store this variable in a JSON file/DB and fetch/update the value there.

Every time you refresh the page the code is going to be reset and variables are included.
To solve this you have to either use a web server and have the variable saved there or find a way to save the variable to the filesystem and load it
back.

The reason the counter is reset constantly is because you're declaring the variable during runtime. There is no persistence to the variable so every time the website is loaded, the variable starts against from 0. Each browser client would keep track of the variable separately so even if you were able to get the variable to persist on your local browser, you would not be able to keep track of the page views from other browsers. The solution to this problem is to keep track of the page views from a centralized server.
You can use a free service such as http://www.webestools.com/pages-views-counter-free-number-pages-views-statistics.html to create the counter that would persist between page views and different clients.

What you need to do is to get the initial value 0 , store in on the server , database or file.
change line var bannerViews = 0; to something like;
var bannerViews = getValueFromServer();
and every after re assigning it, you store it back to the external storage;
For now everytime you refersh the page .
the code var bannerViews = 0; will run and hence bannerViews will alwayz be re assigned to 0

Related

How to keep the value of a variable when the page is refreshed

I'm currently doing a school project where I have to remake a "Pong" type game. I've just started coding, but everything has gone smooth so far. But, I got stuck on this scoring thing. I basically want to keep the value of the variables when the page is refreshed. Some of my code is in french, hence the french words. "Point" is basically the score ( two players so two different scores ). "Fin" is when a player scores. Also, try not judging my code, it's one of the first things I'm doing :P.
Since I'm a complete noob in the coding world, I've tried multiple ways to keep retain the value of the variable when the page refreshes. I've tried cookies and local storage.
var point1=0
var point2=0
if(balle.x+balle.w>=canvas.width){
gameOver=true
player1=true
point1++
}
if(balle.x-balle.w<=0){
gameOver=true
player2=true
point2++
}
function fin1(){
c.font="100px Impact"
c.drawImage(sas,0,0)
c.fillText("Sasuke scores!",200,100)
}
function fin2(){
c.font="100px Impact"
c.drawImage(ita,200,0)
c.fillText("Itachi scores!",200,100)
}
function restart(){
if(gameOver==true){
setTimeout("window.location.reload(false)",2000);}
}
My restart function works, but it just resets the value of the "point1" and "point2" variables everytime the page reloads.
Ahh, I see what's happening here at least what I can understand through your query is:
You are setting data to the local storage but on reset the file runs again and sets the value of point1 and point2 to 0. Basically you are not getting that item from local storage. So what's the solution you ask: write an If condition, If the data is present in local storage then use it, if not then initialize to 0 something like this.
var point1 = localStorage.getItem('point1') ? localStorage.getItem('point1') : 0;
var point2 = localStorage.getItem('point2') ? localStorage.getItem('point2') : 0;
You can get more insight on localStorage from:
MDN localStorage
web-storage
Note: I am considering that you are storing the data(point1 and point2) in the localStorage

setting a variable in javascript to be used in another form

I have form with a Grid (telerik), i think the technology behind it doesnt matter. I let user click on a row in the grid. During the click I extract a value from the Grid with Javascript, like so:
function RadDrillDoubleClick(sender, eventArgs) {
var Code = eventArgs.getDataKeyValue("Status");
if (Code == "In Progress" || Code == "")
{
location.href = "Main1.aspx?mode=edit&DID=" + eventArgs.getDataKeyValue("D_ID");
}
else {
location.href = "Main1.aspx?mode=view&DID=" + eventArgs.getDataKeyValue("D_ID");
}
}
After user has clicked the grid, I call this JS function and send them to correct .aspx page with either VIEW or EDIT mode dependent directly on the Code.
What I'm trying to do is once I get to the Main1.aspx page, I want to be able to continue to hold the CODE value, because when users performs a certain action, I'll need to call a javascript function and use the actual CODE to determine what the user will be able to do.....
var Code = eventArgs.getDataKeyValue("Status");
is there any way I can somehow create like a GLOBAL Variable called
CodeValue
that I can pass around to another form without doing it in the URL?
When the browser navigates to a page, all current JavaScript is unloaded from the browser. This means any functions/variables, etc. will not be accessible on the new page unless you've persisted the value in some way.
Common ways of persisting the value include:
Add it to the query string of the URL the user is navigating to
Save the value to a cookie
Save the value to local/session storage
For your scenario, #1 is probably your best bet (keep in mind the user can have multiple browsers/tabs open to your site).
One way to get the value from URL is like this: on the page Main1.aspx, you add to your JavaScript a function that will run after page loads and that will get what it needs from the current URL
var globalValue; // variable that will receive the value from URL
window.onload = function() {
var thisURL = window.location.href;
globalValue = url.split("?").pop();
// this will store in globalValue everything that comes after the last "?"
// example: if the url is www.site.com/text?value, it will store string "value" to globalValue
};

Google Tag Manager - Count amount of pageviews

I've made an event in Google Tag Manager, which triggers when a specific page is loaded.
The Event label is the value of my user defined variable SearchCounter with type: Custom JavaScript.
In 'SearchCounter' I have the following JS:
function(){
var counter;
if(localStorage.getItem("count_search") === null || localStorage.getItem("count_search") === 'undefined'){
localStorage.setItem("count_search", "1");
return localStorage.getItem("count_search");
}
else{
counter = parseInt(localStorage.getItem("count_search"));
counter = counter + 1;
localStorage.setItem("count_search", counter);
return localStorage.getItem("count_search");
}
return localStorage.getItem("count_search");
}
When I don't have the item in my local storage already, it still give's me 7 instead of 1. Then I'll press F5: count_search = 17, And again f5: 27. A CTRL-F5 gives me 37.
It should be 1, 2, 3, 4, 5 etcetera.
I hope someone can help me to implement a counter-alike function in Google Tag Manager, so I can send the amount of searches to GA, when a goal has been achieved. So, When someone clicks a specific button a would like to get the value of count_search, to send it to GA within an event.
Thanks very much.
First of all this metric is given by google analytics by default so i don't see why ur trying to store it somewhere else. If you dont want the avg that google uses you can just store a custom dimension at 'Session' level with the sessionID and those in a custom report open Sessions by pageviews. Here is info about it.
On the other hand, if you insist doing it your way i think even if this works it isn't the best approach you would get a much better result storing the counter in a custom dimension at 'Session' level. (It ll overwrite the value each time for a given session and you ll end up with the last one send)
Hope it helps.
What you need to do is changing the name of the parameter saved in the localStorage. I don't know why, but count_search does not work. I tested your setup and encountered the same weird effect where the count_search item is summing up to astronomical numbers. Using a different name like thisIsMyPageViewCounter works just fine though! Probably count_search is accessed by another object in the document or window and you managed to get a value out of it by chance.
If you want to add the page view count to an event, I do not see any other way than creating both a Custom HTML Tag to set the counter and a Custom JS Variable to return the count.
This is the Custom HTML Script to be added to each page view:
<script>
(function() {
if(localStorage.getItem("thisIsMyPageViewCounter") === null || localStorage.getItem("thisIsMyPageViewCounter") === 'undefined') {
localStorage.setItem("thisIsMyPageViewCounter", 1);
} else {
var counter = 0;
counter = parseInt(localStorage.getItem("thisIsMyPageViewCounter"));
counter = counter + 1;
localStorage.setItem("thisIsMyPageViewCounter", counter);
}
})();
</script>
This is the Custom JS Variable to be added as a value to the event:
function() {
pageviewCounter = parseInt(localStorage.getItem("thisIsMyPageViewCounter"));
return pageviewCounter;
}
I hope this helps!

using localstorage to keep html on page refresh not working

I'm trying to integrate this fiddle: http://jsfiddle.net/jaredwilli/ReT8n/ in a fiddle I'm doing:
https://jsfiddle.net/vlrprbttst/99c8gn7k/
Basically you have a basket with some items inside of it, you can add or remove them. What I want is that, on page refresh, the html() of the .basket is kept in local storage. I'm stuck here:
https://jsfiddle.net/vlrprbttst/z8cffk4c/
I've put the forLocalStorage variable in the click handler because otherwise, the var wouldn't update itself but now I'm guessing that the final local storage code
if(localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
}
is not working because it can't retrive the variable?
I've tried moving around things but I'm stuck here. what am i doing wrong?
You need to update DOM once your variable is set, e.g:
// LOCAL STORAGEEEEEEEE
if (localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
$('#cart').html(forLocalStorage);
itemsCount();
}
Local storage can only store string key value pairs. I ensured you are passing in a string and also added a function to populate the cart on refresh, which resolved problems.
function populateCart() {
var items = localStorage.getItem('toDoData') || '';
$('#cart').html(items);
}
Added this call inside document.ready, like so: -
$(document).ready(function() {
populateCart();
// rest of code
});
Working CodePen: http://codepen.io/owenayres/pen/oxKmZg
You can do some light reading here on local storage. It is, in my opinion, best practice to store the data for the HTML as some JSON in local storage, which you would then loop through and regenerate the HTML for when reading this data again.

Variable not updating in script string, yet it updates

Very confused here.
I have a search box which reads a list of school names from my database. When I select a school, the id (from the db) gets put in a hidden textbox.
I also have a search box which reads a list of courses from my database. However, I made the query so that it only reads the courses from the selected school.
It does that, in theory.
I was planning to pass the school id, which I grab from the hidden box, to the search script which in turn passes it to my database query. However, the variable I put my school id in doesn't seem to be updating.. yet it does. Let me explain.
I come on the page. The school for my test account has id 1. The id number in my hidden box is indeed 1. I search for a school which I know has some courses assigned to it: the id number in the box changes to 3.
I have a JS variable called school_id which I declared outside of my $(document).ready. I assume that means it's global (that's what I got taught even though SO told me once it isn't really the correct way to do this. Still have to look into that). I wrote a function which updates this variable when the school search box loses focus:
$("#school").blur(function() {
school_id = $("#school_id").val();
});
A quick javascript:alert(school_id); in my browser bar also shows the updated variable: it is now 3 instead of 1.
Onto the search script part of my page (excerpt of the script):
script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&"
As you can see, I pass the school_id variable to the script here. However, what seems to be happening is that it always passes '1', the default variable when the page loads. It simply ignores the updated variable. Does this string get parsed when the page loads? In other words, as soon as the page loads, does it actually say &id=1? That's the only idea I can come up with why it would always pass '1'.
Is there a way to make this variable update in my script string? Or what would be the best way to solve this? I'm probably missing out on something very simple here again, as usual. Thanks a lot.
EDIT
Updated per request. I added a function getTheString as was suggest and I use the value of this function to get the URL. Still doesn't work though, it still seems to be concatenating before I get a chance to update the var. HOWEVER, with this code, my ajax log says id:[object HTMLInputElement], instead of id:1. Not sure what that means.
<script type="text/javascript">
var school_id;
$(document).ready(function() {
$("#school").blur(function() {
school_id = $("#school_id").val();
});
// zoekfunctie
var scholen = {
script:"/profiel/search_school?json=true&limit=6&",
varname:"input",
json:true,
shownoresults:false,
maxresults:6,
callback: function (obj) { document.getElementById('school_id').value = obj.id; }
};
var as_json = new bsn.AutoSuggest('school', scholen);
var richtingen = {
script: getTheString(),
varname:"input",
json:true,
shownoresults:true,
maxresults:6
};
var as_json2 = new bsn.AutoSuggest('studierichting', richtingen);
});
function getTheString() {
return "/profiel/search_richting?json=true&limit=6&id=" + school_id + "&";
}
</script>
This is because the URL is static, it is not updated as the ID changes.
You should update the URL as part of the code you wrote to get the ID:
$("#school").blur(function() {
school_id = $("#school_id").val();
// update URL here ...
});
Aren't you concatenating script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&" before the event is fired and the var updated?
Okay. So the problem was my third party plug-in instead of the code I wrote. I fixed this by editing the code of the autoSuggest plugin so it now includes my id field in the AJAX request.
var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp)+"&id="+ $("#school_id").val();
Thanks to everyone who tried to help me out!

Categories