Solved

How to create a session variable for my website and a button to clear it?

Posted on 2011-03-20
11
183 Views
Last Modified: 2012-05-11
Hey guys, I created a web page where someone visits the site a pop up box askes for their name, they are then greeted good morning, afternoon depedning on the time of day. Trouble is, leaving the homepage to visit other pages athen going back to the homepage the pop up box asks again for a name. How Can I have my web page so once it has the visitors name it will not ask again until the browser is closed and once a name is eneterd a button will appear to the side in case it is someone else visiting the site then the "Not you" button vlears the session and the pop up box again asks for a name.

I have tried to do this by mnyself but I am having troubles.

Here is the javascript which I am suing for this page:

//---------------To prompt for a username on the home/index page only----------------------------------------------
function getUsername()
{
	username = window.prompt("Please enter your name","");
	return username;


//--------------This is used to determine the time of day when greeting the user only on the home/index page only------------------------------------------------

	datetoday = new Date();
	timenow=datetoday.getTime();
	datetoday.setTime(timenow);
	thehour = datetoday.getHours();
	if (thehour > 18) display = "Evening ";
	else if (thehour >11.59) display = "Afternoon ";
	else display = "Morning ";
	var greeting = ("Good " + display + username + "!");
	document.write(greeting); 
	


<p><script type="text/javascript"> document.write("<strong>Good " + display + getUsername() + "! Welcome to my Website</strong>");</script></p> 
}

Open in new window



Any help is appreciated!!
0
Comment
Question by:deucalion0
  • 6
  • 5
11 Comments
 
LVL 12

Expert Comment

by:Amick
ID: 35175897
Using a cookie is the most general way to solve the problem, however HTML5 allows persistent variables, and if you are in an environment where you can control what browsers your users employ that might be an easier solution.
0
 
LVL 12

Expert Comment

by:Amick
ID: 35175942
W3 Schools has a couple of articles that might be useful to you in this:

JavaScript Cookies

and

HTML 5 Storage

They provide examples that do approximately what you're trying to do.
0
 

Author Comment

by:deucalion0
ID: 35176010
Thank you Amick I shall look at those articles now, I appreciate it!
0
 

Author Comment

by:deucalion0
ID: 35176461
Hey, so I spent a couple of hours trying to get this to work. The actual code on the W3 schools is helpful, my problem is merging it with my existing code. OK, so I have a prompt box for the user, the name input gets added to a line of text and input in a paragraph as a greeting on the web page, I need the name enetered into the new code in place of this I can't figure it out.

Here is the code I have which displays the greeting:

<p><script type="text/javascript"> document.write("<strong>Good " + display + getUsername() + "! Welcome to my Website</strong>");</script></p> 

Open in new window


The pieces of code that do this:

function getUsername()
{
	username = window.prompt("Please enter your name","");
	return username;
}

	datetoday = new Date();
	timenow=datetoday.getTime();
	datetoday.setTime(timenow);
	thehour = datetoday.getHours();
	if (thehour > 18) display = "Evening ";
	else if (thehour >11.59) display = "Afternoon ";
	else display = "Morning ";
	var greeting = ("Good " + display + username + "!");
	document.write(greeting); 

Open in new window



Here is the new code I am trying to merge with this:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
  
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

Open in new window


All I need is a prompt, the user enters a name and the hello good morning username! is displayed, the next time the page is loaded, if it is afternoon now then good afternoon username!

In the body of the page I use this to lrun the above cookie code:

<body onload="checkCookie()"> 

Open in new window


I am almost there, it is just tricky trying to get things to display on screen instead of alert boxes!


Thanks!
0
 
LVL 12

Expert Comment

by:Amick
ID: 35178195
The best thing would be to use a checkCookie to replace function getUsername()

function checkCookie()
{
var username=getCookie("username");
if (username=null || username="")
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
return username;
} 

Open in new window


Then all of the rest of the program should operate the same.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:deucalion0
ID: 35179065
Hey Amick, I tried exactly as you suggested and it doesnt work now the code does nothing, I don't know why this just stops working. Could it be as the code that figures out the time of day isnt in a function and I use document.write in the html?

like this:

	datetoday = new Date();
	timenow=datetoday.getTime();
	datetoday.setTime(timenow);
	thehour = datetoday.getHours();
	if (thehour > 18) display = "Evening ";
	else if (thehour >11.59) display = "Afternoon ";
	else display = "Morning ";
	var greeting = ("Good " + display + username + "!");
	document.write(greeting); 

<p><script type="text/javascript"> document.write("<strong>Good " + display + checkCookie() + "! Welcome to my Website</strong>");</script></p> 

Open in new window


I think the error may llie in there somewhere but Iv'e tried everything!

Thanks for your patience!
0
 
LVL 12

Expert Comment

by:Amick
ID: 35181285
I've written an example page for you. Give it a try.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>EE Example</title>

<script type="text/javascript">

function getUsername()
{
var username=getCookie("username");
if (username==null || username=="")
  {
    username=prompt("Please enter your name:","");
    if (username!=null && username!="")
    {
      setCookie("username",username,2);
    }
  }
return username;
}
function getGreeting()
{
	var datetoday = new Date();
	var timenow=datetoday.getTime();
	datetoday.setTime(timenow);
	var thehour = datetoday.getHours();
	if (thehour > 18) var display = "Evening ";
	else if (thehour >11.59) display = "Afternoon ";
	else display = "Morning ";
	var greeting = ("Good " + display + getUsername() + "!");
	return(greeting);
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
/* This function is no longer used */
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }

else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

</script>
</head>

<body>


<p><script type="text/javascript">
	document.write("<strong>" + getGreeting() + " Welcome to my Website</strong>");
</script></p>

</body>
</html>

Open in new window

0
 

Author Comment

by:deucalion0
ID: 35181404
Amick that is excellent, thanks so much for that! it works just as I wanted, I am alomst there! The two things I need to happen is that when I close the browser the cookie is deleted, so that the prompt for username is opened again, and that I can put a button on the page next to the display paragraph so that the user can manually clear the cookie and re enter a name in case it is a different user from the same computer using the same browser. i am researching how to do this now, any suggestions is appreciated, the code you provided was a great help, thank you!!!
0
 
LVL 12

Accepted Solution

by:
Amick earned 500 total points
ID: 35182164
This will be harder to do, I think.  You'll notice that on sites like Amazon and eBay they'll have a question like "Not deucalion0? Click here."

To expire a cookie try:
function expireCookie()
{
  var username=getCookie("username");
  if (username!=null && username!="")
    {
      setCookie("username",username,-1);
    }
}

Open in new window

0
 

Author Closing Comment

by:deucalion0
ID: 35182379
Excellent advice, the replies in this question, together helped me build the perfect solution to my problem!

Thank you Amick, really appreciate it!!!!
0
 

Author Comment

by:deucalion0
ID: 35182395
Amick, thanks a lot for your help on this, you helped a lot! I just created a button and added the code you provided to delete the cookies, I then added a fucntion to reload the window, so when the user clicks the Not you? button it reloads the window, the username prompt box is reloaded and the new username can be entered. This is exactlywhat I was looking for, I could not have accomplished this without your assistance!

Thank you!!!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now