Using localStorage for pagecount hits - javascript

For the life of me I can’t figure this out grrr and wondering if someone could help…
My son is doing some html homework. We’re trying to put a page counter that will count and display the number of hits to a page. He’s got an index and three other pages. I’ve put this on each page:
<div class="page-count">
<script type="text/javascript">
if (localStorage.pagecount)
{
localStorage.pagecount=Number(localStorage.pagecount) +1;
}
else
{
localStorage.pagecount=1;
}
document.write("You've had "+ localStorage.pagecount + " hits.");
</script>
</div>
Problem is it counts all of the hits together rather than how many hits per page… how could I get this to count the hits on a single page rather than how many hits in total?
Thanks in advance.

localStorage is domain wide and its values are shared across your entire site, not just one page on that site. localStorage values are also only kept in users' browsers and not on the server hosting your website. Keep this in mind if you are building a page counter.
If you use localStorage to keep count, you will only be keeping count of a particular user's visits to that page from a specific computer.
If this is indeed the functionality you are looking for, you can make it work by giving each of your individual pages a separate key within the pagecount object.
Something like:
// If this is the first time someone has visited your site, you want
// to check to see if pagecount has been defined. If not, define the pagecount object.
!localStorage.pagecount ? localStorage.pagecount = {} : '';
var currentPage = window.location.href;
if(localStorage.pagecount[currentPage]){
localStorage.pagecount[currentPage] = Number(localStorage.pagecount[currentPage]) + 1;
}
else{
localStorage.pagecount[currentPage] = 1;
}
The above gives your pagecount object a key for every page that exists on your site.

Because localStorage works across all pages under the same domain they will count the same number.
If you'd like to differentiate them you could try something like this:
var url_segment = window.location.href.split('/');
var script_name = url_segment[url_segment.length - 1];
if (localStorage[script_name]) {
localStorage[script_name] = parseInt(localStorage[script_name]) + 1;
}
else {
localStorage[script_name] = 1;
}
document.write("You've had "+ localStorage[script_name] + " hits.");
Note that I did not want to use the entire path as my key, only my script name. You can most likely use the entire path, I just thought this was prettier.

Related

Localstorage mistake, best way to correct?

I am still abit of a noob and I made a site with an admin panel where I made the option to change the price showed on the front page.
However I have made this with Localstorage and it works great but it probably wont show for other visitors right?
My current Localstorage code:
<script>
function save(){
var gpprice = document.getElementById('gpvalue').value;
localStorage.setItem("price", gpprice);
}
</script>
<script>
function save3(){
var gpprice3 = document.getElementById('gpvalue3').value;
localStorage.setItem("price3", gpprice3);
}
</script>
And to display it on the front page:
<script>
window.onload = function() {
document.getElementById("product-price1").innerHTML = "$" + localStorage.getItem('price') + "/M";
document.getElementById("product-price2").innerHTML = "$" + localStorage.getItem('price3') + "/M";
}
</script>
It works really good for me and I would like a similar system.
So I guess my question is how can I correct this oopsie? Should I use MySQL instead to store the value? Or is there a way to still use this?
No one else can access your localstorage data. You need to store it in a database.

Saving the output of the output of a random array?

So this function works fine, however everytime i refresh the page the WINNER (person1 to 4) changes, i want to save the output and have it FIXED so that it wont change everytime i refresh..
Basicly: There is a timer on my website and when it hits 0 , it should automaticly pick someone from the list as the winner... but the winner should appear on the website for everyone and stay there
function randomNavn(){
document.getElementById("utskrift").innerHTML = "";
for (i = 0; i < 1; i++){
randName.push(nname.splice(Math.floor(Math.random() * nname.length), 1));
}
document.getElementById("utskrift").innerHTML = randName.join(", ");
}
var nname = ["Person1", "Person2", "Person3", "Person4"],
randName = [];
You need server-side code to do this -- and most likely a database. You can't do what you want from JavaScript. Each person's browser will run that javascript and get their own answer, bit it is only on their browser. Someone else will get a different answer, etc. That's not what you want to happen I assume.
To save data more permanently to be used in a web page, you have a few options:
Create a web service that accepts POST or PUT requests and saves the data on a server. This will allow you to share data between users.
Use a cookie. This will only save a value for each user's session. It won't share data between users.
You could use localStorage:
$window.localStorage.setItem('initData', {data: 'here'}
after some nights spent i've managed to found the perfect solution.
1) I've eliminated the javascript function for the array and instead craeted a php file where a winner or more is choosed.
2) From that php file we write the winners into a text file.
3) From that text file we read it through ajax and list it when countdown is over.
If anyone is ever in need, its good solution.
Thanks for everytning

Javascript file for multiple html pages

I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.

How to make a web app retain information?

Ok... so a user enters info into the journal field and hits submit, and a function gets called on the information they have submitted, which I call changeTextComment(). That function calls another function and so on as the info is formatted and placed in the cue, as in a Facebook commentary.
I need this information saved so it can be recalled later, in local storage, making the app not refresh every time I restart it. So...
<script>
function appCache() {
// Check browser support
// this is experimental for local storage...
more here: http://www.w3schools.com/html/html5_webstorage.asp
if (typeof(Storage) != "undefined") {
localStorage.setItem(para);
// Retrieve
document.getElementById("journal").innerHTML = localStorage.getItem(para);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
};
</script>
So looking at the appCache function it seems like it might work except I need to identify what the key variable is that will be stored and then retrieved.
I think this is the variable userInput, as any time the user hits the 'add to journal' button this variable is used to store the user input and then put into the changeTextComment() function.
I am wondering if this is the simplest way to deal with this whole thing... I do not yet understand databases, but wondering if that would be easier to learn.
In this case, I would add the function Appcache() to the function changeText() such that it caches the variable and then how would I set it up to then feed the value of the variable's cached info into changeText() upon launch of the app?
Every submission to the journal will have a unique value.
Heres the ChangeTextComment() Function... still sorting out how to use classes in css to simplify these functions:
function changeTextComment(){
// to be modified from the above to change the location of the dump
var userInput = document.getElementById('userInput').value;
// get the input from the user
var panel = document.createElement("div"); // create a parent divider for everything
// assignment of attributes
panel.setAttribute("class","panel panel-default panel-body");
panel.setAttribute("id","panelBody");
var para = document.createElement("P");
var t = document.createTextNode(userInput);
para.appendChild(t);
// add comment area
var c = document.createElement("INPUT");
c.setAttribute("type", "text");
c.setAttribute("id", "comment");
c.setAttribute("placeholder", "comment here");
c.setAttribute("class", "form-control input-lg");
// add comment button attempt -- success <> now try to put it in the textarea
var d = document.createElement("INPUT");
d.setAttribute("type","button");
d.setAttribute("class","btn btn-info active pull-right");
d.setAttribute("onclick","commentThis()");
d.setAttribute("value","Add Comment");
panel.appendChild(para); // this is where a comments piece would go
// place the item
var destination = document.getElementById("journal")
//destination.insertBefore(Commentaryarea, destination.firstChild);
//destination.insertBefore(panel, destination.firstChild);
destination.insertBefore(panel, destination.firstChild);
panel.appendChild(c);
panel.appendChild(d);
document.getElementById("userInput").value = "";
document.getElementById("userInput").focus();}
</script>
<script>
function setText(a){
document.getElementById("userInput").value = a
document.getElementById("userInput").focus();
}
</script>
When you say "stored locally", do you mean stored in the visitors browser, i.e. with only themselves being able to see it and retrieve it? Or do you want other users to be able to see the data, and/or the commenter to be able to see it if they log in later from another location?
If it's the latter then you need to store it on the server side, and you're going to need a database for that. If all you need is to store journal entries then mongoDB is easy to set up with javascript, but if you have a lot of relations (journal entries being associated with users, comments on entries being associated with users and entries, ect) then perhaps an SQL database would suit you better.

Checking if a URL contains a value with javascript

I am working on a feature for my site that allows the user to use the back button and not have to load more database results.
I start by loading 16 results, and then there is a load more button which loads the next 16. In the ajax success i change the href of this button so the url changes to e.g. domain.com/#1 to #2.
I wrote this last night:
// First get the page URL and split it via # signs
var parts = location.href.split('#');
// now we run a check on the URL and see how many 'parts' there are
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '&';
}
location.href = parts[0] + mark + 'page=' + parts[1];
}
Which gets the URL, and redirects the user the same page but converts the fragment number to a page number. From this i then use a PHP $_GET and set the limit claus last value from that.
This works fine. But its primitive. Let for instance say i push back and the URL becomes:
www.domain.com/?page=1
If i then click to load some more data, the page url becomes:
www.domain.com/?page=1#2
If the user then visits another page and comes back then they get directed to:
www.domain.com/?page=1&page=1
Whats the best way around this? I was thinking of running a check on the URL at the same time as looking for a fragment and if the URL has a page variable i then add that variable to the fragment variable and the page URL becomes ?page=THE SUM NUMBER
Any help on modifying the snippet i posted above to check the URL for a page value and then add the two together before the redirection?
Thanks!
You need to use location.search to get the query string on a URL:
var queryParameters = location.search.split('&');
Then you can loop through the queryParameters and check if page is set:
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
Please see the documentation on the MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You might also find this example useful for returning one value:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.236.3A_Get_the_value_of_a_single_window.location.search_key.3A
If you want to get the information after the #, you need to use location.hash. The MDN documentation I linked also has information on location.hash.

Categories