I am creating a simple website using HTML and JavaScript in dreamweaver. On my home page, I want to show an alert (whenever my home page loads), which says that "Hello, you are visitor no. 12. Welcome to my site!". I want this visitor number to change on every page load of home.html.
I basically want the visitor no. to be stored in a cookie and increase the no. by 1 in the cookie every time the page refreshes.
How can I create such an alert? Please help. Thanks.
Also, I want to know if I add this functionality, would it be an example of dynamic content on a web page or do you HAVE to create database connections and all in order to create dynamic content. Wouldn't this idea of creating cookie also an example of dynamic content?
Edit-1
I want that only. How many times page was visited. I am a beginner and want it all simple. I just want to know how I can store the no. of visits in a cookie and then retrieve that value from that cookie and show it in an alert on page load. Thanks.
If you want to store the number of visitors, you'll need to use a backend scripting framework (PHP, Ruby, Rails, Python, etc) to store the number of visits your page has received in a database. The javascript of displaying the actual number is simple, with alert('message');
If you just want the number of times that specific user has visited, based on their local information, here's a simple solution:
if (localStorage.numVisits)
numVisits = localStorage.numVisits;
else
numVisits = 0;
alert("Welcome, you have visited " + numVisits + " times before.");
localStorage.numVisits++;
To make it really simple for you (without using the database) you can store the number in a .txt file in the server, and use a simple scripting language like PHP to send it in a hidden field to the client. Every time the PHP page runs, it will have to get the current number and increment it. Something like this:
$myFile = "counter.txt";
$fh = fopen($myFile, 'r');
$count = fgets($fh);
$count++;
fclose($fh);
$fh = fopen($myFile, 'w');
fwrite($fh, $count); // write the incremented counter
fclose($fh);
echo "<input type='hidden' id='counter' value='$count'>";
Then, you would have to get this counter value from the javascript (client side) and alert to the user.
var visitCount = document.getElementById('counter');
alert("Hello, you are visitor no. "+visitCount+". Welcome to my site!");
A Cookie is always Client-sided! You can't do it that way. The easiest way to accomplish what you are looking for is to write a simple php counter which reads a number from a file - adds one and writes it back as soon as your page is viewed.
Check google for examples on "counters".
There actually is no way to count clientsided ALL the visitors you have or had - the client can't know that your server was visited x times ;)
for that you need to create the table and every time when session is start u need to increase +1 in there table and alert the visitor no.
table like
id : no
-------
1 : 3
2 : 5
and massage like
echo "
<script type=\"text/javascript\">
alert(\"Hello, you are visitor no. {$row["no"]}. Welcome to my site!\");
</script>
";
You cannot keep a global page view count in a cookie. A cookie is stored in one user's browser and is local only to that browser. All a cookie could show would the page views that occurred in that one single browser.
Page view counts across all viewers must be done at the server level and then the information put into the page when the page is requested. There are some free ways to put page view counts into the page using the free service level of services like StatCounter.
Or, you'd have to implement a counter in your own server that was serving the page (with the count probably stored in a persistent database) and then insert the current count into the page each time it is requested. For just page count information, it's probably easiest to just go with a service like Statcounter.
Cookies are not persistent across different visitors. To give every visitor a visitor number, you need something stored on a server. If you cannot access server-side functions, use a visitor counter - https://www.google.com/#hl=en&q=visitor+counter
Related
I try to make a view counter in js for my webpage.
When you view the page, the counter will increase with 1.
The counted numbers are displayed.
But one thing is not working: When I view the website from another device, the counter starts at 0.
So I used localStorage to store the data. But I want when I see the page from my laptop, the counter increases by one. And when I view the page from my phone the counter should already show the number one and should increase it with one ,so the counter will be 2.
I don't know how to make it workable. It's only done with LocalStorage. I thought I should save the data, by storing the data in a .txt file, but it does not work because when the filewriter save the datas (1) into the file, it will save the next view (1) next to the previous number. And if I want to add the current number to the previous it will show number 1.
Here's my code:
var n = localStorage.getItem('profile_1_tech.html');
if (n === null) {
n = 0;
}
n++;
localStorage.setItem("profile_1_tech.html", n);
document.getElementById('counter').innerHTML = n;
<span><span id="counter"></span> Views</span>
So I need to result be added (1 view + 1 view for each view), and all the user can see the same number.
The JavaScript LocalStorage API is only meant to be used on one device, and using the SessionStorage API would be of even less use because that memory is cleared as soon as the tab is closed.
As your question tag has PHP included what you can do is create an account system that increments a value that you would store in a SQL table using PHP, and every time a user creates an account you would create a new "views" field just for them.
However if you are trying to use a view counter for analytical purposes to see how many people use your website then I can suggest using Google Analytics because it is free and requires very minimal code as opposed to my aforementioned "account system" approach with storing the views in a database with PHP.
I have this code in my website
<?php
// This is to check if the request is coming from a specific domain
$ref = $_SERVER['payskip.org'];
$refData = parse_url($ref);
if($refData['host'] !== 'payskip.org') {
// Output string and stop execution
die("Hotlinking not permitted");
}
echo "Executing code here";
?>
and it does what it should do, if you visit the site without the given referrer it will show "Hotlinking not permitted", but if you visit it from payskip.org it will execute the given code.
So far so good, but if I refresh my page with f5 or the reload button it executes the code again! I want it to execute only once and if you refresh it should go back with the hotlink is not permitted.
Well, what your server needs is a way to remember the visitor. You could do this via many ways but let me state the two most common:
1. Sessions
2. Database.
If you are only interested in stopping the 'refresh browser' hack, using sessions should solve your problem but what happens when the same user visits your site some other time after the session must have ended?... In such a scenario, you might want to also remember such a user...and that's where database comes to the rescue.
Is it possible to find out, how many people have visited your website?
I am looking for solution using Javascript or HTML.
If the user is on my website, it should count +1.
I have no idea and have not tried anything yet.
You can't possibly do it using JS or HTML because you do not have persistent storage. Meaning, once the client is closed all information is lost.
You're going to either need a database to keep track of how many people have visited your website (MySQL + PHP) or something along those lines
OR
You can use an external source such as google analytics which will do everything and more for you.
What you need to do is use persistent data storage. You can use a server side language like PHP to store data in the database or you use write to a file, then retrieve the data using AJAX requests to make it dynamic. As JavaScript is client side you can't do it.
Simple Overview
On load send request to PHP script to increment counter.
Then in that PHP script return the number of views and manipulate the DOM using JavaScript and display it.
Unique Visit Counter
You'd get something like the visitors IP and check if they have visited the site before (you'd insert the IP in to a table) and compare the users IP with the ones in the table.
try to use this code in php:
<?
Session_start();
$today = time();
$query="INSERT into logged_in (Today, SessionID, CurrentPage, BrowserType, IP) VALUES ('".$today."','".$_SESSION['sesid']."','".$_SERVER['PHP_SELF']."','".$_SERVER['HTTP_USER_AGENT']."','".$_SERVER['REMOTE_ADDR']."')";
$result = mysql_query($query);
?>
but you need also logged_in table. I hope this help you!
I am developing a Question & Answer website where a user is presented five puzzles on a page and the score is calculated using JavaScript as he attempts the questions on the page. The score is saved in a Javascript variable score. I have a paging system like this:
Now when the user clicks on 3 I want to send the variable score to the next page, where I have require scoreUpdateInDatabase.php on each such page such that the score of previous page is made permanent to the databse and the following PHP script presents him the next 5 questions.
How can I pass that score variable in secure way? I can't use GET because the user will modify it. I am satisfied with POST if this can be used, even though POST data can be modified but I just want minimal security.
P.S. Please do not suggest making AJAX call where in one side I will send score and while returning carries next 5 questions. I don't want to use AJAX to refresh content because it is not SEO friendly.
The simplest solution would be cookie based. Writing the value to a session cookie and the reading it.
You could use jquery cookie. It also gives you the option to require https if desired.
Save it in a session. POST would work equally well in this particular case but my preference would be storing it in the session.
The only secure way to do this is to pass the actual answers to the server using a POST or AJAX, do the calculation of the score also on server side and keep it in a SESSION variable.
More information on sessions in PHP
Try looking into Jquery - You should be able to return the value to the server scripting language (as you listed PHP as a tag, I assume you're using PHP). By using Jquery, you can get the javascript variable to the form BEFORE submitting the form to the next page.
Assuming you have used PHP to generate the form to submit initially rather than create the form in javascript. I would use Jquery - to get this file ( http://jquery.com/ ) and to include("jquery.js"); etc... in your PHP script for it to be used.
I would then convert the javascript variable(s) to a php variable and assign this to a hidden field in the form to be submitted to the next page using a $_POST[] variable.
However It will not be SEO friendly (POST and SESSION is not SEO friendly, but you should use them, continue reading)
We are talking of a game. No-one want that the Search engine index the last page of a game... because everyone can search on google (for example) for the last page of your game without playing.
You have to use ajax or post, but don't let google index every page of your game. It's nonsense.
Only the first page of your game should be indexed.
I have 2 pages where the user gives data that needs to be stored (the 1st is a string from the first page and the rest comes from a form from the second page). This webpage is not on a server, its on a laptop without any connection to the internet. The plan is for all that data to be written on to a text document.
My question is; can I send the first variable to a JavaScript like var = get.element... and then redirect the user to the second page where more variables get sent to the same JavaScript without the first disappearing. Because from what I have understood, all the scripts and variables "reset" when reloaded.
Extra, this is how I plan to write the info in a text file, does it look good or is there a better way to store data locally?
<?php
function createFile(){
$file = 'D:\test.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
Thanks for all your time!
I would think to pass some parameters from the first page using GET or POST request to the second page.
For example:
//yourApp/second_page.php?name=John Smith
is requested from the first page so you can get the data in the second page using $_GET['fname']
The solution #shadow proposed (using html5 local storage api) seems more clean and simple tho.