Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New to the CF scene
    Join Date
    Jul 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Javascript - First Time Visitor Tracking Cookie

    Having trouble completing this cookie tracking code.

    The script needs to:
    1. Display a text message for first time visitors - (You are a first-timer)
    2. Display how many times a user has visited - (You've been here ... times)
    3. Display date & time of users last visit - (You last visited on...)

    I need help completing the "first time visitor" code. I have the code in place for the other two requirements, but don't know how to implement this one.

    Here is what I have so far:
    Code:
    <script type="text/javascript">
    
    	    now = new Date
    	    expireDate = new Date
    	    expireDate.setMonth(expireDate.getMonth()+6)
    	   
    		hitCt = parseInt(cookieVal("pageHit"))
    		hitCt++
    		lastVisit = cookieVal("pageVisit")
    		if (lastVisit == 0) {
    			lastVisit = ""
    		}
    		
    		document.cookie = "pageHit="+hitCt+";expires=" + expireDate.toGMTString()
    		document.cookie = "pageVisit="+now+";expires=" + expireDate.toGMTString()
    		
    		function cookieVal(cookieName) {
    			thisCookie = document.cookie.split("; ")
    	  	    for (i=0; i<thisCookie.length; i++) {
    	  	        if (cookieName == thisCookie[i].split("=")[0]) {
    	  	        	return thisCookie[i].split("=")[1]
    	  	        }
    	   	    }
    			return 0
    		}
    		
    </script>
    </head>
    <body>
    	<script language="Javascript" type="text/javascript">
    	
    		document.write("You have visited this page " + hitCt + " times.")
    		if (lastVisit != "") {
    			document.write("<br />Your last visit was " + lastVisit)
    		}
    		
    		// End hiding script -->
    	</script>

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Just for starters, you are going to be taken to task big time in this forum for using document.write( ) and language="Javascript" and for your "end of hiding script" stuff, all of which are about 10 years or more out of date. And Felgall will chide you for putting your <script> in the <head> of your page, instead of just before the </body> where it will be simpler and make the page run faster.

    And then finally, I'll want to rewrite your cookie reading code to make it much more efficient.

    So....
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    216
    Thanks
    0
    Thanked 29 Times in 27 Posts
    It's not a good idea to show that visitors are spied...

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    How about this?
    Code:
    <!DOCTYPE html>
    <html>
    <body>
    <div id="visitMessage"></div>
    
    <script type="text/javascript">
    ( 
      function( )
      {
          // get a reference to the message div: 
          var msg = document.getElementById("visitMessage");
    
          // first, convert document.cookie into something usable:
          var cookies = [ ]; // collection stored here
    
          var parts = document.cookie.split("; ");
          for ( var p = 0; p < parts.length; ++p )
          {
              var pair = parts[p].split("=");
              cookies[ pair[0] ] = decodeURIComponent(pair[1]);
          }
     
          // *NOW* it's a usable collection:
          // Okay, has this person been here before?
          var lastVisit = cookies["pageVisit"];
          var visitCount = 0; // assume not visited
    
          if ( lastVisit == null )
          {
              // nope...so start him off right:
              msg.innerHTML = "Welcome, new visitor!  Please come again soon.";
          } else {
              // how many times has this person been here?
              visitCount = Number( cookies["pageHit"] );
              // and give a message:
              msg.innerHTML = "You have visited this page " + visitCount + " times.<br/>"
    			+ "Your last visit was " + lastVisit;
          }
          // regardless of first or not, set the cookie:
          var exp = new Date( );
          var mn = exp.getMinutes();
          if ( mn < 10 ) mn = "0" + mn;
          var now = (exp.getMonth()+1) + "/" + exp.getDate() + "/" + exp.getFullYear()
                  + " at " + exp.getHours() + ":" + mn;
          exp.setMonth(exp.getMonth()+6); // expire in 6 months?
          document.cookie = "pageHit=" + (visitCount+1) + ";expires=" + exp.toGMTString();
          document.cookie = "pageVisit=" + now + ";expires=" + exp.toGMTString();
      }
    )();
    </script>
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    pincher.12 (07-29-2013)

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by 007julien View Post
    It's not a good idea to show that visitors are spied...
    ?? Anybody who uses the internet and is dumb enough to think they are NOT spied upon deserves whatever happens to them.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    New to the CF scene
    Join Date
    Jul 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you soooo much Old Pendant for the quick and thorough reply to my question! I very much appreciate that you took the time write code for me and to add explanatory comments as well. These will really help me to understand whats going on in the script. I need that.

    I am also grateful for your honesty about using outdated code and old comments in my posting. And, I didn't know about putting the script just before the body for better efficiency. Yes, as you have surmised, I am brand new at coding javascript. I will endeavor to do a better job in the future.

    All the best to you!

  • #7
    Senior Coder
    Join Date
    Sep 2010
    Posts
    1,899
    Thanks
    15
    Thanked 226 Times in 226 Posts
    If you're using php on your server, php reads cookies like a dream. JS and php are equally good at writing them, but php much excels at reading them, it treats them like an array, and you can transfer that data to javascript very easily.
    PHP Code:
    if(isset($_COOKIE)) $cookie_data $_COOKIE['my_data'];
    else 
    $cookie_data "welcome new visitor"
    Then you echo the data into javascript.
    Welcome to http://www.myphotowizard.net

    where you can edit images, make a photo calendar, add text to images, and do much more.


    When you know what you're doing it's called Engineering, when you don't know, it's called Research and Development. And you can always charge more for Research and Development.

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,731
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Cookies of this kind are of little value in the case of users who erase their cookies frequently (as I do) - perhaps every day.

    I would have thought the a user would know whether or not he had visited the site before, and would not care much about how many occasions he had previously visited, or when. This sort of script is product oriented - and just says "Look how clever I am at web coding" rather than doing anything of genuine value for the user.


    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #9
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    10,965
    Thanks
    0
    Thanked 236 Times in 233 Posts
    Quote Originally Posted by Philip M View Post
    I would have thought the a user would know whether or not he had visited the site before, and would not care much about how many occasions he had previously visited, or when. This sort of script is product oriented - and just says "Look how clever I am at web coding" rather than doing anything of genuine value for the user.
    There are some cases when this is important. One good example is in online banking. Upon logging in, it tells you when you last visited. This will help you determine if someone else hacked your account.

    And I agree that using cookie is not reliable. If you want to track a user, then you should have a login feature on your site and from there you can track their visits.

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,465
    Thanks
    0
    Thanked 634 Times in 624 Posts
    Quote Originally Posted by glenngv View Post
    There are some cases when this is important. One good example is in online banking. Upon logging in, it tells you when you last visited. This will help you determine if someone else hacked your account.
    That information is tracked based on your login though and the only cookie if there is one at all would be the one that holds the session id. All of the rest of the information is stored together with your user identification in a database on the server.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #11
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    10,965
    Thanks
    0
    Thanked 236 Times in 233 Posts
    @felgall, that was I was saying in my last statement which you removed in your quote.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •