0

So I have an assignment I've been working on for 6 hours. I'm supposed to use JavaScript to create a cookie and display the cookie information on the user profile page of a website.

In attempting this I've written a bunch of code, and ideally I was wanting to use the submit button on the form to initially save the information as a cookie, and then display the same information when the viewer returned to the web page. Failing that repeatedly I've just put information in the cookies. So as long as it works, I don't care how it works, on submit, or with the information I plugged in.

So here's the JavaScript:

<script type="text/javascript" language="javascript">
function setCookie(cookieName, cookieValue, cookiePath, cookieExpires){
    cookieValue = escape(cookieValue);
    if (cookieExpires == ""){
    var nowDate = new Date();
    nowDate.setMonth(nowDate.getMonth() + 6);
    cookieExpires = nowDate.toGMTString();
}
if (cookiePath != ""){
    cookiePath = ";Path=" + cookiePath;
}
document.cookie = cookieName + "=" + cookieValue + ";expires=" + cookieExpires + cookiePath;
}

setCookie("cookieFirstName", "George", "", "");
setCookie("cookieLastName", "MaGoo", "", "");
setCookie("cookieEmail", "[email protected]", "", "");
setCookie("cookieTelNumber", "4095555545", "", "");
setCookie("cookieBirthdate", "12/19/2004", "", "");
setCookie("cookieCity", "Westend", "", "");
setCookie("cookieState", "California", "", "");

function getCookie(cookieFirstName){
var cookieValue = document.cookie;
var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
if (cookieStartsAt == -1){
    cookieStartsAt = cookieValue.indexOf(cookieName + "=");
}
if (cookieStartsAt == -1){
    cookieValue = null;
} else {
    cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
    var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
    if (cookieEndsAt == -1){
        cookieEndsAt = cookieValue.length;
    }
    cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
}
return cookieValue;
}
function yummyCookie(){
  var cFirst = getCookie("cookieFirstName");
  if (cFirst != null){
      document.getElementById("firstname").value = cFirst;
  }
  var cLast = getCookie("cookieLastName");
  if (cLast != null){
      document.getElementById("lastname").value = cLast;
  }
  var cEmail = getCookie("cookieEmail");
  if (cEmail != null){
      document.getElementById("email").value = cEmail;
  }
  var cTelNumber = getCookie("cookieTelNumber");
  if (cTelNumber != null){
      document.getElementById("telnumber").value = cTelNumber;
  }
  var cBirthdate = getCookie("cookieBirthdate");
  if (cBirthdate != null){
      document.getElementById("birthdate").value = cBirthdate;
  }
  var cCity = getCookie("cookieCity");
  if (cCity != null){
      document.getElementById("city").value = cCity;
  }
  var cState = getCookie("cookieState");
  if (cState != null){
      document.getElementById("state").value = cState;
  }
}
</script>

This information was placed in the tags. The body of the website looks like this:

<body onLoad="yummyCookie()">
<div class="wrapper">


<header class="center" id="banner">
    <h1>Lindsey's Pet Picture Paradise</h1>
  </header>
  <aside id="menu" class="floatleft">
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="businessprofile.html">Business Profile</a></li>
        <li><a href="userprofile.html">User Profile</a></li>
      </ul>
    </nav>
  </aside>
  <div id="content" class="center">
  <h1 id="pageheader">User Profile</h1>
  <form id="userprofile">
  <table>
  <tr>
  <td><label for="firstname">First Name: </label></td>
  <td><input type="text" id="firstname"></td>
  </tr>
  <tr>
  <td><label for="lastname">Last Name: </label></td>
  <td><input type="text" id="lastname"></td>
  </tr>
  <tr>
  <td><label for="email">Email: </label></td>
  <td><input type="email" id="email"></td>
  </tr>
  <tr>
  <td><label for="telnumber">Telephone Number: </label></td>
  <td><input type="tel" id="telnumber"></td>
  </tr>
  <tr>
  <td><label for="birthdate">Birthdate: </label></td>
  <td><input type="date" id="birthdate"></td>
  </tr>
  <tr>
  <td><label for="city">City: </label></td>
  <td><input type="text" id="city"></td>
  </tr>
  <tr>
  <td><label for="state">State: </label></td>
  <td><select id="state">
    <option value="al">AL</option>
    <option value="ak">AK</option>
    <option value="az">AZ</option>
    <option value="ar">AR</option>
    <option value="ca">CA</option>
    <option value="co">CO</option>
    <option value="ct">CT</option>
    <option value="de">DE</option>
    <option value="fl">FL</option>
    <option value="ga">GA</option>
    <option value="hi">HI</option>
    <option value="id">ID</option>
    <option value="il">IL</option>
    <option value="in">IN</option>
    <option value="ia">IA</option>
    <option value="ks">KS</option>
    <option value="ky">KY</option>
    <option value="la">LA</option>
    <option value="me">ME</option>
    <option value="md">MD</option>
    <option value="ma">MA</option>
    <option value="mi">MI</option>
    <option value="mn">MN</option>
    <option value="ms">MS</option>
    <option value="mo">MO</option>
    <option value="mt">MT</option>
    <option value="ne">NE</option>
    <option value="nv">NV</option>
    <option value="nh">NH</option>
    <option value="nj">NJ</option>
    <option value="nm">NM</option>
    <option value="ny">NY</option>
    <option value="nc">NC</option>
    <option value="nd">ND</option>
    <option value="oh">OH</option>
    <option value="ok">OK</option>
    <option value="or">OR</option>
    <option value="pa">PA</option>
    <option value="ri">RI</option>
    <option value="sc">SC</option>
    <option value="sd">SD</option>
    <option value="tn">TN</option>
    <option value="tx">TX</option>
    <option value="ut">UT</option>
    <option value="vt">VT</option>
    <option value="va">VA</option>
    <option value="wa">WA</option>
    <option value="wv">WV</option>
    <option value="wi">WI</option>
    <option value="wy">WY</option>
  </select></td>
  </tr>
  <tr>
  <td colspan="2"><input type="submit" value="Save Your Information!"></td>
  </tr>
  </table>
  </div>
  <footer>Safe and friendly place to share your love of your pets with others! Design by Lindsey Schreiner.<br /> Forget your user name or password? <a href="##">Click here for help</a>.</footer>
</div>
</body>

I don't know if I'm placing something wrong or if I've missed something stupid, but I've looked in as many places as I could find. If someone could please help see what ever I've missed I'd really appreciate it, thank you.

4
  • not sure where your problem is but maybe you have to wait with javascript to page content to be loaded? I mean wrapping the whole js in document.addEventListener("DOMContentLoaded", function(event) { //do work }); Commented Jan 20, 2015 at 6:23
  • @andrusieczko - they are already doing it in the onload handler from the <body> tag. Commented Jan 20, 2015 at 6:26
  • Do you see any script errors in the browser error console? Commented Jan 20, 2015 at 6:27
  • I don't have any errors in the console, honestly when I test it in the browser, I just get... blank. It's irking me slightly. Does it need to be on an active web server for it to actually SAVE as a cookie? Commented Jan 20, 2015 at 6:35

1 Answer 1

1

I see three main issues:

1) - You don't have any code to save the currently entered values as new cookie values. You need to change the "Save Information" button to not be a submit button (you don't want it submitting a form to the server) and instead hook up a new function to it that you write that will save each form value to the appropriate cookie.

2) Upon page initialization, you are setting every cookie so any previously saved values can never be used because you always overwrite them every time the page is loaded. You should only save initial cookie values if there are no values already saved.

3) In the getCookie() function, you declare the argument as cookieFirstName, but then appear to be using cookieName in the function:

function getCookie(cookieFirstName) {
    var cookieValue = document.cookie;
    var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
    if (cookieStartsAt == -1) {
        cookieStartsAt = cookieValue.indexOf(cookieName + "=");
    }
    if (cookieStartsAt == -1) {
        cookieValue = null;
    } else {
        cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
        var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
        if (cookieEndsAt == -1) {
            cookieEndsAt = cookieValue.length;
        }
        cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
    }
    return cookieValue;
}

Presumably, it should be this:

function getCookie(cookieName) {
    var cookieValue = document.cookie;
    var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
    if (cookieStartsAt == -1) {
        cookieStartsAt = cookieValue.indexOf(cookieName + "=");
    }
    if (cookieStartsAt == -1) {
        cookieValue = null;
    } else {
        cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
        var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
        if (cookieEndsAt == -1) {
            cookieEndsAt = cookieValue.length;
        }
        cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
    }
    return cookieValue;
}

FYI, I was able to see this error by pasting your code into http://jshint.com/ and looking at its report.


Though personally, I use these well tested cookie functions:

// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/" 
//   and can limit which pages on your site can 
//   read the cookie.
//   By default, all pages on the site can read
//   the cookie if path is not specified
function createCookie(name, value, days, path) {
    var date, expires = "";
    path = path || "/";
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=" + 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);
}

Also, escape() and unescape() have been deprecated and should not be used. You can use encodeURIComponent() and decodeURIComponent() instead.

Sign up to request clarification or add additional context in comments.

7 Comments

Well, good catch on that error, thank you. Unfortunately it still doesn't appear to have fixed the issue. This isn't something that I need to upload on an active web server to see work correctly is it?
@Lindsey - You don't appear to have any code to save the entered values as cookies when the user hits "Save Information". Right now, you have that button labeled as a submit button so it is trying to submit a form. That is not what you want. You want that button to trigger a function that gets all the form values and saves each one as the appropriate cookie value.
@Lindsey - I've documented three separate issues in my answer now.
Thanks on those, I was working from the text book on those parts.
On the code to save information part, I tried that before by putting an onClick event triggering an event that would save them all, but it didn't work either.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.