Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat.

free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class">

Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat. free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class

<Code_Punk>'s

Advanced JavaScript Lesson 34:
Parsing Multiple Cookies

Code Tutorials



Site Development



Downloads



Help!!



Home


Overview

Multiple cookies are handy because they can associate unknown viewer input with a known cookie name. This means we can find the data string by searching for the known cookie name. Multiple cookies can be used to accept data that's entered in no particular order. Parsing can also allow us to ignore unneeded cookies or cookie data that aren't relevant to our current needs.

We've already seen how to set multiple cookies. The important thing is to keep up with the cookies' names. In this lesson, we'll learn how to parse and sort out our cookie data so we can get the specific data an individual cookie holds.

This parsing of multiple cookies occurs in three steps:

1) The whole "document.cookie" is read and split around the semi-colons (;) using the "split()" method. This gives us an array of individual cookies.

2) The cookies are "sorted" using a FOR loop and searching the cookie array for cookie names. Then the individual cookies can be assigned to variables for further processing.

3) The individual cookies are "split()" around the "=" character to remove the cookie's name from its data. The data is then assigned to the variables that will be used in the display or other scripting.

Setting Multiple Cookies

Here's the example we'll be making in this tutorial. The first page accepts viewer input and sets the data on three cookies: "name_cookie=", "addy_cookie=", and "quote_cookie=".

You should already be able to set these cookies. The important part is in giving the cookies different names and keeping up with what type of data is associated with what cookie name. Now lets concentrate on page 2 of the example to see how we read these multiple cookies.

For purposes of example, lets say I filled out the form with a name of "Code Punk", an email address of "code_punk@hotmail.com", and a quote of "I love cats."

My cookie string would read, when unescaped:

name_cookie=Code Punk; addy_cookie=code_punk@hotmail.com; quote_cookie=I love cats.

We'll be seeing how this string is manipulated as we go along in this lesson.

The Initial Read & Split

The second page of our example reads the cookie and displays the information. We need to get three stings assigned to variables for the display. To prevent errors, these variables are set to blank (null) strings when they are declared at the start of the JavaScript (outside any function). Otherwise, if the page was viewed without any cookies set, a "no object" error would occur.

The first thing we need to do when reading multiple cookies is to make sure any cookies exist. This is the code I used:

if (document.cookie && document.cookie !=""){process_cookies()}

else{window.location = "samp167.htm";}

The above checks for the presence of a cookie and to make sure the cookie isn't a blank string. This is done outside of any functions on the page. Cookie detection is usually done as the <head> loads. In this case, it must be done before the page's <body> loads and the cookie data is required.

If a cookie exists, the script goes to a function called "process_cookies()". If no cookies exists, the viewer is redirected to the first page to set them.

My cookies, as described in the above section, would be detected and sent to the "process_cookies()" function.

Once cookies are detected, the "process_cookies()" function begins splitting them up. The first split is around the semi-colons that are placed between the cookies' name=value pairs:

if (document.cookie && document.cookie !=""){process_cookies()}

else{window.location = "samp167.htm";}

function process_cookies(){
//reading and splitting the whole cookie
var whole_cookie = unescape(document.cookie);
var each_cookie = whole_cookie.split(";");
}//ends process_cookie() function

The first statement in "process_cookie()", after the comment, is the line that reads the cookie and assigns the overall string to "whole_cookie". The next line, in red, is the split(). The "whole_cookie" string is split around the semi-colons. This makes "each_cookie" an array of the individual cookies' name=value pairs.

My cookies would be "unescape()d" and assigned to the "each_cookie" array as follows:

each_cookie[0] = "name_cookie=Code _Punk"

each_cookie[1] = "addy_cookie=code_punk@hotmail.com"

each_cookie[2] = "quote_cookie=I love cats."

Sorting The Cookies

Once the cookies are separated into an array of individual cookies, it's time to sort the cookies so we can assign the appropriate data to the variables used in our display. Note that with multiple page forms that can be edited and re-edited by the viewer, we will not always know the order in which the cookies are set. We will not know the order of the name=value pairs. This is why we need to sort them. We begin this by making a FOR loop that will cycle through the "each_cookie" array:

if (document.cookie && document.cookie !=""){process_cookies()}

else{window.location = "samp167.htm";}

function process_cookies(){
//reading and splitting the whole cookie
var whole_cookie = unescape(document.cookie);
var each_cookie = whole_cookie.split(";");

for (i = 0; i < each_cookie.length; i++){

SORTING IFs WILL GO HERE

}//ends FOR

}//ends process_cookie() function

Above is the basic FOR loop. We initialize the counting variable ("i") to zero. Then we count one at a time ("i++") until "i's" value becomes equal to the "length" property's value of the "each_cookie" array.

This will have the loop cycle through each cookie in the array. We can use IF statements in the loop to search for our cookie names and sort out the various values:

if (document.cookie && document.cookie !=""){process_cookies()}

else{window.location = "samp167.htm";}

function process_cookies(){
//reading and splitting the whole cookie
var whole_cookie = unescape(document.cookie);
var each_cookie = whole_cookie.split(";");

for (i = 0; i < each_cookie.length; i++){

if (each_cookie[i].indexOf("name_cookie") > -1){var name_cookie_data = each_cookie[i];}

if (each_cookie[i].indexOf("addy_cookie") > -1){var addy_cookie_data = each_cookie[i];}

if (each_cookie[i].indexOf("quote_cookie") > -1){var quote_cookie_data = each_cookie[i];}


}//ends FOR

}//ends process_cookie() function

Here's the logic behind what we've done. Each cookie is analyzed one at a time with the loop. We use IF statements and "indexOf()" to search for a cookie name. If a given cookie name exists, that individual cookie string - both name and unknown data - are assigned to a unique variable. We can later use this variable for further processing.

The first IF statement uses "indexOf()" to check for the presence of the string "name_cookie". This string will exist in the first cookie, so that cookie's string, including the name, is assigned to the variable "name_cookie_data".

Note that even if there are other unrelated cookies involved in the overall cookie string, the IFs only extract the cookie strings we search for with "indexOf()". Other extraneous cookies are ignored.

Here's how my cookie strings get sorted out:

name_cookie_data = "name_cookie=Code Punk"

addy_cookie_data = "addy_cookie=code_punk@hotmail.com

quote_cookie_data = "quote_cookie=I love cats."

Getting The Data

Sorting cookies gives us variables that are set to the value of the individual cookie strings. The last thing we need to do is to break these individual strings into the cookie's name and its data. We do this by using "split()" and splitting around the "=" sign:

if (document.cookie && document.cookie !=""){process_cookies()}

else{window.location = "samp167.htm";}

function process_cookies(){
//reading and splitting the whole cookie
var whole_cookie = unescape(document.cookie);
var each_cookie = whole_cookie.split(";");

//sorting loop

for (i = 0; i < each_cookie.length; i++){

if (each_cookie[i].indexOf("name_cookie") > -1){var name_cookie_data = each_cookie[i];}

if (each_cookie[i].indexOf("addy_cookie") > -1){var addy_cookie_data = each_cookie[i];}

if (each_cookie[i].indexOf("quote_cookie") > -1){var quote_cookie_data = each_cookie[i];}

}//ends FOR

//splitting data and assigning final display variable

var name_split = name_cookie_data.split("=");
name = name_split[1];

var addy_split = addy_cookie_data.split("="); address = addy_split[1];

var quote_split = quote_cookie_data.split("=");
quote = quote_split[1];


}//ends process_cookie() function

Each cookie goes through the same simple two-step process. First the cookie is split around the "=" sign. Secondly, the second part of the split ([1] - remember that arrays begin counting at 0) is assigned to a variable used in the display. This is the data entered by the viewer.

The cookie data I've been using would be spit and the cookie names ignored. The data would be assigned to variables like this:

name = "Code Punk"

address = "code_punk@hotmail.com"

quote = "I love cats."

These are the strings I need for the display.

The "Edit" Function

Another feature of our example is the ability to go back to the main page and have our current cookie data displayed in the form's boxes. This code is on the first page - the one the form is on. It simply detects and reads any cookies by using the parsing technique described above for page 2. It assigns the final strings to the various form boxes' values.

Any edited data will overwrite the old cookie data. In this case, all of the cookies are rewritten (overwriting the old cookies) with each submit, so putting the old cookie data into the form insures that old data, even unedited, will be re-written to the new cookies.

Summary & Exercises

The strength of using multiple cookies is that it associates unknown viewer input with a known cookie name. This name can be used to parse the appropriate data values into known variables for use on other pages.

The first step in parsing multiple cookies is to read and "unescape()" the whole "document.cookie". Split() this around the semi-colons (;) to make a array of individual cookies.

The second step in parsing multiple cookies is to use a FOR loop to cycle through the array of individual cookies. IF statements are used in this loop to detect known cookie names using "indexOf()" and assigning cookie strings to known variables for further processing.

The final step in parsing multiple cookies is to split the sorted, individual cookies around the "=" sign. The second part of this array is the data the viewer entered. This can be assigned to a variable for display or further processing.

A popular use of cookies in general is to provide an editing function where previous values are entered into a form for editing. This uses the parsing technique described above if multiple cookies are used. Care must be taken when coding an editing script that old, unedited data is re-written to the new cookie.

Make a sample page like the one we've been using. Change the order in which the cookies are written and you'll see that the output results on page 2 are the same. This is the power of being able to parse and sort multiple cookies. This becomes more apparent as we move on to multiple page forms and a JavaScript shopping cart script.

For practice, try making multiple cookies that each hold more than one piece of data. This means making multiple appended cookies. The trick is to remember to add a demarcation scheme to each cookie that will hold multiple data. After the multiple cookies are parsed, you'll have to parse the individual data strings with further "split()s" around your demarcation flags.

Don't worry if you get confused trying this. It's the topic of our final cookie lesson.



To Next Advanced JavaScript Lesson

Back To Advanced JavaScript Index