Page created 9 May 2005, updated 13 June 2008.
JavaScriptPage 3 This article is about using cookies with JavaScript. I HATE COOKIES You can't use comas, semi-colons, or white spaces, so you have to 'escape' the characters. You have to use a string 'expires=' and separate it from the other data, with a 'semi-colon', in order to set the life time of the cookie. I also find that JavaScript makes using cookies more difficult than PHP and Perl. However, since JavaScript works on the client side, it is necessary to use it. CREATING A COOKIE The script uses 3 strings, name, address, mail, and separates them with '||', before combining them into everything. The create cookie function takes 3 arguments, cookie name, value, and expiry time in seconds. This script creates 2 cookies, but they are stored in only 1 file. <script type= "text/javascript"> //==================================================== create cookie function cook(name, value, time){ var expiry = new Date(); expiry.setTime( expiry.getTime() + time * 1000 ); var expire = expiry.toGMTString(); document.cookie = name + "=" + escape(value) + ";" + "expires=" + expire; } //================================================================== //================================= Create cookie data var cookie_name = "cook1"; var cookie_name2 = "cook2"; var time = 60; //number of seconds var name = "My_name"; var address = "My_address"; var mail = "jim@daftwat.biz"; var everything = name + "||" + address + "||" + mail; //============================================ send data to create function cook(cookie_name, everything, time); cook(cookie_name2, "example cookie data", time); </script> RESTORING THE DATA The script below returns the data from the cookie, back to the original strings, name, address, and mail. It also restores the second cookie data, and the result is displayed in 2 alert functions. <script type= "text/javascript"> //=============================================== has a cookie been set? if( document.cookie ){ //=========================================== get cookie data var cookie_data = document.cookie; var user_data = cookie_data.split( "=" ); //============================================= need cook1 if( user_data[0] == "cook1" ){ var user_data2 = user_data[1].split( ";" ); var user_data3 = unescape(user_data2[0]); var user_data4 = user_data3.split( "||" ); //=============================================== restore original names var name = user_data4[0]; var address = user_data4[1]; var mail = user_data4[2]; } //============================================= alert names alert( "Name: " + name + "\nAddress: " + address + "\nEmail: " + mail ); //====================================================== alert cook2 value alert( "Second cookie data: " + unescape(user_data[2]) ); } </script> PHP There is a similar cookie script in the PHP section. Personally, I find that the languages are very similar, and learning another language, actually leads to a better understanding of them all.
|