JavaScript Redirecting

The following is another example of how to use cookies. It is not an active example. This example uses JavaScript to redirect a user based on a cookie. It is used to determine if a user has already taken a poll and redirect the user based on the results of the determination. The user will receive the form to fill out to take the poll or will receive the current status of the poll. This example uses the date functions to set expiration dates on cookies, along with setting the cookies, and testing to see if the cookies have been set on the client computer. The target of the link is determined based on cookie status.

Code and functions in the HTML Header

<SCRIPT LANGUAGE="JavaScript">
<!--
 function nameDefined(c,n) {
 var s=removeBlanks(c)
 var pairs=s.split(";")
 for(var i=0;i<pairs.length;++i) {
 var pairSplit=pairs[i].split("=")
 if(pairSplit[0]==n) return true
 }
 return false
}
function removeBlanks(s) {
   var temp=""
   for(var i=0;i<s.length;++i) {
      var c=s.charAt(i)
      if(c!=" ") temp += c
   }
   return temp
}
function getCookieValue(c,n) {
   var s=removeBlanks(c)
   var pairs=s.split(";")
   for(var i=0;i<pairs.length;++i) {
      var pairSplit=pairs[i].split("=")
      if(pairSplit[0]==n) return pairSplit[1]
   }
   return ""
}
function testCookie(cname, cvalue) {
   var cookie=document.cookie
   if(nameDefined(cookie,cname)) {
     tvalue=getCookieValue(cookie,cname)
     if (tvalue == cvalue) return true
	  else return false
   }
   else return false
}
function redirectLink() {
   if (testCookie("ospoll1", "done")) {
      window.location="/cgi-bin/oscharpl.pl?display"
   }
   else{
		var futdate = new Date()
		var expdate = futdate.getTime()
		expdate += 3600*1000
		futdate.setTime(expdate)
		var newCookie="ospoll1=start; path=/;"
		newCookie += " expires=" + futdate.toGMTString()
		window.document.cookie=newCookie
		if (testCookie("ospoll1", "start"))
		{
      	window.location="../ospoll1.html"  //Display the HTML page with the poll
		}
		else
		{
			window.location="/cgi-bin/oscharpl.pl?display"  //Display the poll results
		}
   }
}

// -->
</SCRIPT>



How to call the code to do a Link Redirect

This code may be placed anywhere in the body of the HTML:

<A HREF="javascript:redirectLink()">Redirect</A>