Overview
In this tutorial, we'll be making a very simple shopping cart as in this example. Play around with this a while. You'll notice that no editing functions are available other than going back to the "order pages" and resetting the cookie.
Each "order" page sets it's own cookie. Each of these cookies is a demarcated string containing the cookie's name and the values of the items selected ("Put In Shopping Cart").
The actual "shopping cart" page reads and parses both of these cookies just like we have been parsing multiple cookies. Furthermore, it uses the arrays made by using "split()" on the cookies to make a "looped display". Lets get started by making the "order" pages and setting the cookies.
Setting The Cookies
Setting the cookies is done in two simple steps in a single function. The "Put In Shopping Cart" links all point to a "place()" function. They also pass a parameter, like "Ultra Widget", indicating what item is to be put on the cookie:
<a href="javascript:place('Ultra Widget')">Put In Shopping Cart</a>
The "place()" function does two things: 1) It builds a string of items to write to the cookie, and 2) it sets the cookie. The cookie is updated (overwritten) with each click of the "Put In Shopping Cart" links. Here's the code in the <script> of each order page's <head>:
var widgets_string = "";
function place(new_item){
widgets_string = widgets_string + "xxx" + new_item;
document.cookie = "widgets=" + escape(widgets_string);
}
First note that we initialized the variable "widgets_string", which will hold our list of items, with a null string (""). We did this outside the function making it a global variable. If we set it to null each time the function was run (inside the function), it would not append to itself, but overwrite the older data. In the function's parentheses, we've added a variable "new_item" to receive the parameters passed by each link.
Each time a "Put In Shopping Cart" link is clicked and this function is run, "widgets_string" adds to itself. Not only does it add new items, it also adds "xxx" to separate the data, or demarcate the string. We'll use this to sort out the items when the cookie is read.
Finally, the cookie is set. The important thing to notice here is that the cookie's name is "widgets=". The new "widgets_string" is added and the cookie is overwritten with new data each time a "Put In Shopping Cart" link is clicked.
The "ninja page" uses an identical script except the cookie's name is "ninja=" instead of "widgets=". This is what makes it a separate cookie.
Note: In this example, if you click the same "Put In Shopping Cart" link several times, it will keep adding another string for that item on the cookie.
Reading The Cookies
The shopping cart page does two things. First it tests and processes the cookie data. Secondly, it displays that data using a loop to make the HTML display. The process begins by detecting and splitting a cookie just like any other multiple cookie read.
For the sake of example, lets say we've ordered a "Red Widget" from the widget page and some "Kaltrops" and a "Mask" from the ninja page. When these cookies are read by the shopping cart page, it looks like this (unescaped):
"widgets=xxxRed Widget;ninja=xxxKaltropsxxxMask
The initial process begins just like reading any other multiple cookie. We detect the presence of a cookie and send the script to a "process_cookie()" function. The first part of this function splits the whole cookie into individual cookies using the semi-colon(s) ";". Then the individual cookies are sorted with a FOR loop and "indexOf()" to place each cookie in a unique variable.
After sorting, our individual cookies are assigned to "whole_widget_cookie" and "whole_ninja_cookie" respectively. Things now look like this:
whole_widget_cookie = "widgets=xxxRed Widget"
whole_ninja_cookie = "ninja=xxxKaltropsxxxMask"
Note that the demarcation ("xxx") is in front of each item. This will allow us to remove the cookie's name and break down the data in one split() around the "xxx":
if (whole_ninja_cookie != ""){
ninja_array = whole_ninja_cookie.split("xxx");
...
The above would make "ninja_array" a list of three items:
ninja_array[0] = "ninja="
ninja_array[1] = "Kaltrops"
ninja_array[2] = "Mask"
We've separated the name from the data in one statement. We can ignore the cookies name and loop through the data by simply beginning the display loop (or any other processing loop) at 1 instead of 0.
The "widget_array" works the same way:
if (whole_widget_cookie != ""){
widget_array = whole_widget_cookie.split("xxx");
...
This would break the "whole_widget_cookie" into:
widget_array[0] = "widgets="
widget_array[1] = "Red Widget"
Making The Display Loop
To display our data, we just make a couple of FOR loops and loop through "widget_array" and "ninja_array". The sum total of all of our processing has left us with one of two conditions for each cookie. The cookie can have legitimate data to display, or it is a null array. If either array is null, we don't run that loop.
The loops are coded in our <body>:
<body>
...
<script language="JavaScript">
//widget array
if (widget_array != ""){
for (i=1; i < widget_array.length; i++){
document.write("<h3>" + widget_array[i] + "</h3>");
}//ends display FOR
}//ends widget display
//ninja array
if(ninja_array != ""){
for (i=1; i < ninja_array.length; i++){
document.write("<h3>" + ninja_array[i] + "</h3>");
}//ends FOR
}//ends ninja display
</script>
...
The first thing to note is that each FOR loop is nested inside an IF statement. These IFs detect if the array contains any data or is null. If either array is null, it is ignored and the loop doesn't run.
Next, notice that the count begins at 1, not 0. This is because the first element of both arrays ([0]) is the cookie's name, not needed data.
The loops go through each cookie's data and displays the data in <h3> tags. Later, we'll be using similar loops to make table rows and do other automatic layout routines.
Our sample cookie would provide the data:
widget_array[1] = "Red Widget"
ninja_array[1] = "Kaltrops"
ninja_array[2] = "Mask"
The "document.write()" statements would place each of these data between <h3> tags for display.
You should be familiar with the cookie killing routine. Make sure to kill these cookies before moving on to another cookie tutorial.
Summary & Exercises
A simple shopping cart, like our example, sets and reads multiple cookies with multiple data from multiple pages. After mastering this, you've learned just about all you can do with a cookie - and that's a lot!
Start out a project like this by making the pages that set the cookies. Test each cookie's content individually. It's almost always a good idea to reset the cookie each time the data changes.
Reading these cookies is just like reading any other set of multiple cookies. You might want to begin your "read" page by letting it display the whole cookie and then whittle your way down to the actual data and display you want as a final result.
Always keep in mind what would happen on your "read" page if there is no cookie to process. I've been initializing the arrays that will hold my final data to null strings and using them to detect the absence of data. There are a lot of other ways to go about this.
For practice, try adding a third page and cookie to our example and getting it to work right along with the other two.
To Next Advanced JavaScript Lesson
Back To Advanced JavaScript Index
|