dkype
dkype

Reputation: 23

Javascript Cookie Redirect

When people type in my URL, I want them to click North Carolina or Virginia. After they click, it redirects them to either www.myurl.com/nc or www.myurl.com/va. After they answer that question, next time they visit my site, it will redirect them to the appropriate page without clicking NC or VA again. Here's what I've got so far. I feel like I'm close, but I honestly have no clue what I'm doing.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
   <title></title> 
</head>
<body> 
   <a href="#" onClick="window.location = "http://www.myurl.com/nc"" value="nc">North Carolina</a>
   <br />
   <br /> 
   <a href="#" onClick="window.location = "http://www.myurl.com/va"" value="va">Virginia</a> 
   <script type="text/javascript" src="script.js"></script> 
   <script type="text/javascript">
      function setCookie {
         document.body.style.state = size; 
         createCookie('state', size, 90);
      }
      var state = readCookie('state'); 
      if (state !== null)
      { 
         // cookie exists setCookie(state);
      } 
    </script> 
</body> 
</html>

I also have separate script file with the following code:

// JavaScript Document 
function createCookie(name,value,days) {
    if (days) {
       var date = new Date(); 
       date.setTime(date.getTime()+(days*24*60*60*1000));   
       var expires = "; 
       expires="+date.toGMTString(); 
    } else var expires = "";
    document.cookie = name+"="+value+expires+";
    path=/"; 
}
function readCookie(name) { 
    var nameEQ = name + "=";
    var ca = document.cookie.split(';'); 
    for(var i=0;i < ca.length;i++) {
        var c = ca[i]; 
        while (c.charAt(0)==' ')
           c = c.substring(1,c.length); 
        if (c.indexOf(nameEQ) == 0) 
           return c.substring(nameEQ.length,c.length);
    } 
    return null; 
} 
function eraseCookie(name) {
    createCookie(name,"",-1);
}

Upvotes: 1

Views: 9414

Answers (1)

sachleen
sachleen

Reputation: 31131

onClick="window.location = "http://www.myurl.com/nc""

is wrong because you have double quotes within double quotes. Make the inside ones single quote ('). When the user clicks a link, it should call a javascript function with a parameter of which site the user wants to visit.

// state will be wither "nc" or "va"
function redirect(state) {
    createCookie('state', state, 90);
    window.location.href = "http://www.myurl.com/" + state;
}

In the future, if the cookie is already set, redirect the user using the same method as in the function above.

Upvotes: 1

Related Questions