Hour 11. Advanced Programming

For just about the first half of this book, you’ve learned the methodology and mindset of effective programmers. While all the examples and discussion have covered JavaScript code, most of these concepts are fairly universal. Even better, the syntax of loops and conditional expressions that you learned are directly applicable to other languages like C, C++, and Java. If you want to move to Visual Basic, you just need to tweak your syntax a bit, but by learning the concepts, you’re already most of the way there.

The last hour was not general programming, but more specific to what JavaScript can do to improve your website. This hour will cover more of the same, specifically adding improving the user’s experience with cookies. After this hour, you will jump into object-oriented programming (OOP), as covered in Java.

The highlights of this hour include:

Image Defining cookies

Image Writing cookies

Image Reading cookies

Image Deleting cookies

JavaScript’s Programming Weakness

When you program, an important skill to master is file management. All the great data-manipulation code in the world has little value if you are not saving the information to a file for later use. Programs that read data are limited if the data is hard-wired into the code or must be entered by the user. The real power of data-management programs often come from when they can read data from a disk file, make changes, and then write the altered or new information to a disk file. For this reason, most programming languages come with a robust set of file-management functions and methods.

This is not the case with JavaScript. There are severe limitations to the language’s ability to create files on the computer’s disk system. If you think about the general purpose of JavaScript, this limitation makes sense. If you are browsing the web, you don’t want to give any site you visit the ability to start placing files on your hard drive. In the best-case scenario, your hard drive would start to fill with junk you probably don’t want. In the worst-case scenario, unscrupulous and malicious hackers could wreak havoc on your machine. So some security is in order, otherwise people would probably turn off JavaScript in their browsers.

There is an exception to this rule. If you have websites you visit regularly, you often want them to remember vital information, including shopping history, preference, and in many cases usernames and passwords if you visit sites that restrict access to registered users. JavaScript can accommodate these needs thanks to cookies.

Snacking on Cookies

Not only are cookies delicious, they make your web-browsing life so much easier. When you patronize a site regularly, you don’t want to waste your time re-entering your key information. If you buy products on a site, it’s great to have your mailing address saved. Or if you looked at 10 products and put them in a shopping cart to consider purchasing later, most of the time you’d like those items to remain in your cart until you decide to either purchase them or manually remove them from your cart, even if you come back to the site weeks later.


Note

Cookies are a sweet name, but I always thought these files should have been called breadcrumbs, as they can lead the user back to their original state, like Hansel and Gretel tried to do with breadcrumbs in the original fairytale.


It you’d like to see how many cookies you have, they are generally located in your Temporary Internet Files. You will probably be a bit surprised with just how many are there. I don’t like messing with files in that folder, so I made a copy of one and pasted it into my documents folder. Opening it with my text editor, here’s what the file looks like:

B
8q7et8l8ihvh5&b=3&s=d6
yahoo.com/
2147484672
2019565568
30429292
1498382404
30282220
*

Fairly unreadable to you and me, right? The only thing that’s clear from this jumbled collection of letters and digits is the website that placed this cookie on my hard drive, yahoo.com. But yahoo can take this cookie the next time I visit it, parse the information contained within it, and know certain information about my most recent visit. This knowledge will make for a smoother return trip for me, and you should want that for your web visitors as well.

So if you’ve created a commerce site, you need to add the capabilities for cookies into your web pages in order to maximize the value and interest in your site. Cookies are small files that your JavaScript program can leave on a user’s computer, containing information that your web page can read and use the next time the user visits.


Note

As you may know, users have the ability to turn cookies off in their browsers—so you cannot assume cookies will be there.


In addition to not saving cookies in the first place, sometimes users delete cookie files when cleaning up their computers. So if you plan on integrating cookies into your website, you will have to write code that can work either with or without cookies—sounds like a job for our favorite conditional statement, if!

Accessing Cookies via document.cookie

If you are looking to create cookies, you need to work with the cookie property of the document object. Cookies are limited stings of data. A cookie consists of a name and its set value:

username=Rebecca

Cookies can store multiple pieces of information, allowing you to keep additional data. For example, you can store the last time the user visited your site, or if you had three stores, you can remember which store location is the closest to your visitor. Then when they return to your site, you can use this data to make their web experience more personalized. Think of it as similar to patronizing a restaurant repeatedly and the feeling you get when they greet you by name and know your favorite dish.

Cookies do have some limitations. Spaces are not allowed in them and many of the punctuation characters, including parentheses, exclamation points, the number sign, and the dollar sign, are not allowed. Before you think no characters other than digits and letters are allowed, it’s not that simple (is it ever?)—you can use the at symbol (@) as well as +, -, and /, as well as a few others. Don’t worry about memorizing which symbols can and cannot be used in a cookie; JavaScript has built-in methods that replace the not-allowed characters with their hexadecimal equivalent as well as a second method that will convert a cookie with hexadecimal characters back to their original values. For example, if you ask a user for their first name, and they enter “Mary Lou”, setting the string through the escape method will turn the string into “Mary%20Lou”. The % symbol is a clue that the next two digits represent a converted character—in this case, 20 is a space. You may be able to guess from this that the percent symbol (%) is also a not-allowed character in cookies, and % is changed to %25.


Tip

You may be saying, “Whoa! What the heck is hexadecimal?” It is a number system that has the digits 0–9 plus A through F. So while 1–9 are the same as our base-10 number system, the number after 9 isn’t 10, it’s A (or 0A as you will often see it). 11, 12, 13, 14, 15, 16, 17 is 0B, 0C, 0D, 0E, 0F, 10, 11 in hexadecimal. If this explanation isn’t helping, don’t fret. You ultimately don’t have to worry about getting hexadecimals right—your computer takes care of it for you.


Just as escape(string) will turn a specific string into an acceptable format to be stored in a cookie, unescape(string) will take a converted string and turn it back to normal. This will become more clear when you see the code example later in this hour.

The Parts of a Cookie

While the lesson mentioned that a cookie consisted of a name and a value, there is more to cookies. Table 11.1 lists the different parts of a cookie, as well as their corresponding value.

Image

TABLE 11.1 The properties of a cookie

Writing Cookies

To write a cookie, you just need to set a string with the data above to the document.cookie. The following small function is a simple chunk of code that asks for a name and then saves it as a cookie:

function writeCookie()
{
       var custName = prompt("What is your name?");
       //Now make sure all characters in the name are cookie legal!
       cookieName = escape(custName);
       //Will now set a cookie with a cookieName of name
       // and a cookieValue of the cookieName string post escape method
       document.cookie = "name=" + cookieName;
       alert("We've created the cookie name="+cookieName);
}

If you put that function in the header of an HTML file and then call it from the body of your HTML file, you will be prompted to enter a name. If you enter a standard first name, you’ll see that name. So I’m going to enter my stage name, D!J Skribble23(), a combination of letters, numbers, and a few odd punctuation marks. JavaScript will tell me it is setting the cookie name=D%21J%20Skribble23%28%29.

However, this cookie will expire as soon as the browser closes. That’s not a valuable cookie. Let’s say you want to keep the cookie for about three months after it’s created. To do that, you need to add the following code lines to your function above (after the alert line, but before the closing brace):

      var expDate = new Date();
      expDate.setTime(expDate.getTime() + (90*24*3600*1000));
      var expireDate = expDate.toUTCString();
      document.cookie += "; expires="+expireDate;

Hopefully these lines aren’t too confusing. The first line creates a variable named expDate and populates it with today’s date using the new Date() method, which automatically sets your variable to the current day and time. However, we don’t want that to be the expiration date—we want the cookie to not expire until 90 days in the future. So we will use the setTime method to set a new time on our expDate variable by using the getTime method to get the current time and then add enough to move the time 90 days in the future. That’s what that string of numbers does. It takes the number of days (90) times the number of hours in a day (24) times the number of seconds in an hour (3,600) times the number of milliseconds in a second (1,000). Thankfully, JavaScript will do all that multiplying for you. Now expDate has the time 90 days in the future, but as mentioned in Table 11.1, the time must be in UTC format. Luckily, JavaScript has a method that will do that conversion for you, toUTCString. Now you can use the concatenation operator (+=) to add an "expires=" and your expiration date to your cookie, which has a name and an expiration date.

Great, so we can easily set a cookie name with little work. But how valuable is that if we cannot read the cookie’s value and do something with it. The next section discusses how to read cookies.

Reading Cookies

To read a cookie, you have to write code that can make sense of the string in the document.cookie attribute. If it’s just a simple “name=value” single-cookie string, that would be straightforward. However, things like that are rarely straightforward, and you need to be prepared to deal with more complicated data (or no data at all, if your web visitor has deleted cookies or not allowed cookies to be saved in the first place). Luckily, if the data is complicated thanks to the presence of additional attributes like the ones listed in Table 11.1, JavaScript has a number of string methods that make your data-reading life easier.

How will you know if you have multiple attributes in your cookie string? Each is separated with the semicolon. JavaScript has a method that splits a larger string into an array of smaller strings, using a character you specify. For example, say you have the following cookie string:

cookieString="name=Sandy;domain=www.jamemc.com;path=/documents";

If you use the split method and assign it to an array as follows:

var cookieArray = cookieString.split(";");

you would create a 3-item array with the following elements:

cookieArray[0] = "name=Sandy";
cookieArray[1] = "domain=www.jamemc.com";
cookieArray[2] = "path=/documents";

You are now in a position to look for a specific name=value pair within your array of cookie values. You just need to loop though the elements of the array and check whether the beginning of a specific element matches the name you are looking for. The following readCookie function will loop through the exploded out array created from document.cookie and check whether the name= exists within the code

function readCookie()
{

        // Get all the cookies pairs in an array
       var cookarray  = document.cookie.split(';'),

        // Now set up the element we want to find
       cooksearch = "name=";
       //Loop through the array elements
       for(var i=0; i<cookarray.length; i++) {
              var startcook = cookarray[i];
              if (startcook.indexOf(cooksearch) == 0) {
                      var aa = cooksearch.length;
                     var bb = startcook.length;
                     Cname = unescape(startcook.substring(aa, bb));
                     alert("Found cookie! " + Cname );
              }
       }

}


Note

Testing this type of code can be difficult on a local machine, as many browers will not allow local files to fully load for security reasons. Loading the sample program onto a web server is the most effective method for testing.


This code will loop through each of the pieces of your document.cookie and search for a substring that matches the one you are looking to find. Using a for loop that goes from 0 to the number of elements in the array, each element is checked whether they’re a match. If there is, a new variable, Cname, is set to the string (after you’ve run the unescape() method on the substring to ensure there weren’t any character conversions when the cookie was initially saved). This code then generates an alert box to tell the user the name was found, but that’s a poor use of the information. It would be far better to return Cname to the point in the code.

Deleting Set Cookies

If you’d like to delete a cookie in JavaScript, all you need to do is set the expire to a time in the past. That will trigger the browser to delete the cookie as it has expired.

For example, to change the date to 90 days before, you can use the same code as last time, but subtract our mathematical formula instead of adding it:

function deleteCookie() {
       var expDate = new Date();
       expDate.setTime(expDate.getTime() - (90*24*3600*1000));
       var expireDate = expDate.toUTCString();
       cookieString += "; expires="+expireDate;
}


Note

The screen in Figure 11.2 looks a bit different than the one in Figure 11.1 because I checked the code with two different browsers, Chrome (Figure 11.1) and Internet Explorer (Figure 11.2). It works under both, but it is nice to double-check and see the subtle display differences that occur depending on what browser a visitor uses to come to your site.


One additional code note here. Again this program uses the onload() function during the body declaration. However, I wanted to load two distinct methods—both the scrolling message box method scrollingMsg() and the new method to check for a cookie checkCookie(). So I created a new holding method loadfunctions(), which is called when the page loads and it in turn, calls my two methods. You can put several functions in such a holding function, but don’t overdo it as it can slow the loading time of your page.

Summary

In this hour, you learned how to personalize the web-browsing experience of your visitors using cookies. While you do occasionally hear some people complain about cookies, they are a common part of the web-browsing experience and almost every page you surf will place cookies on your device. With the ever-increasing speed of processors and size of storage, the amount of lag created by these extra files is imperceptible.

As mentioned at the beginning of the hour, this is almost your last foray into JavaScript. You will now jump to a section on OOP using Java before then surveying some additional programming languages and Internet-development tools—if you are missing JavaScript by then, you will be reunited for one last lesson. You can also go in other directions with JavaScript by picking up a tutorial like Sams Teach Yourself JavaScript in 24 Hours, which will teach you how to use JavaScript libraries, as well as how to add animation and multimedia files to your web pages using JavaScript.

Q&A

Q. Should I worry about the security of cookies?

A. The fears about the security of cookies are largely overblown. Cookies will share aspects of your browsing history with web developers, but they will not share secure information like passwords and account numbers.

Q. How many cookies can I create on my website?

A. While you can create multiple cookies on a website, there is a limit of 20 cookies and 4 kilobytes of cookie data. For most small websites, this is more than enough cookies and storage space. If you find a need to go over the former, you can use some clever methods to store multiple pieces of information in a single cookie, but that is a bit beyond the scope of this book. The information, if you need it, is easy to find in other JavaScript tutorials, and involves combining information into a single cookie and then breaking it back up when you read the cookie.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. What is the value of cookies to web pages?

2. True or false: The following line of code would set a cookie for a visitor’s name:

cookie.document(visitorname==bob);

3. What punctuation character separates different cookies and cookie attributes?

4. What attributes must be in all cookies?

5. If you use the expires attribute, what format must the date be in?

6. How do you delete a cookie?

7. Why do you need to use the escape() and unescape() methods when reading and writing cookies?

8. True or false: All cookies must have the secure attribute set.

Answers

1. Cookies allow a website to remember specific data so the visitor doesn’t need to re-enter the information.

2. False. The cookie property belongs to the document type, not the other way around. Second, you need to use the assignment operator (=) instead of the equality operator (==). The correct format is

document.cookie = "name=bob;";

3. You use the semicolon (;) to separate different cookies or cookie properties.

4. The cookieName and cookieValue attributes must be in all cookies.

5. For all cookies, the expiration date must be set in Universal Coordinated Time (UTC).

6. Set the expiration date for the cookie to a time that has already passed.

7. Certain characters are not allowed in a cookie, so the escape() method converts those characters to hexadecimal format. When reading a cookie, the unescape method will turn those hexadecimal-formatted characters back to their original format.

8. False. The secure attribute is optional.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.132.99