RadianT tutorials, tips and tricks

About cookies

Posted on 2008-Jan-28 at 06:28 in Web programming

About cookies

A "cookie" is a small piece of information sent by a web server to store on the hard disk of a web browser client so it can later be read back from that browser client. This is useful for keeping specific information. An example is when a browser stores your passwords and user IDs. They are also used to store preferences of start pages.

A server, when returning an HTTP object to a client, may also send a piece of state information which the client will store. Included in that state object is a description of the range of URLs for which that state is valid. Any future HTTP requests made by the client which fall in that range will include a transmittal of the current value of the state object from the client back to the server. The state object is called a cookie.

This mechanism provides a tool which enables a host of types of applications to be written for web-based environments. Shopping applications can store information about the currently selected items, fee services can send back registration information and free the client from retyping a user-id on next connection, sites can store per-user preferences on the client and have the client supply those preferences every time the site is connected to. More specifically, uses are varied:

Online ordering systems
An online ordering system using cookies remembers what a person wants to buy even if the visit gets terminated.

Site personalization
This allows people to select an option, and from then on (until the cookie expires) the site guides them in viewing their chosen option.

Web site tracking
Site tracking can show you dead end paths, places in your website that people go to and get lost so to speak. It can also give you more accurate counts of how many people have been to pages on your site. You could differentiate 50 unique people seeing your site from one person hitting the reload button 50 times.

Targeted marketing
This is probably one of the main uses of cookies, they can be used to build up a profile of where you go, what adverts you click on and this information is then used to target adverts at you. Cookies can also be used to store which adverts have been displayed so the same advert does not get displayed twice.

User IDs
In Internet Explorer the first part of the cookie is your win95 log-in name. User IDs can also be remembered, such as IE5.0+ uses.

How cookies work

A command line in the HTML of a document tells the browser to set a cookie of a certain name or value. Here is an example of some script used to set a cookie. A cookie is introduced to the client by including a Set-Cookie header as part of an HTTP response, typically this will be generated by a CGI script.

Syntax of the Set-Cookie HTTP Response Header

This is the format a CGI script would use to add to the HTTP headers a new piece of data which is to be stored by the client for later retrieval.

Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. This is the only required attribute on the Set-Cookie header.
 
expires=DATE
The expires attribute specifies a date string that defines the valid life time of that cookie. Once the expiration date has been reached, the cookie will no longer be stored or given out.

The date string is formatted as:

Wdy, DD-Mon-YYYY HH:MM:SS GMT

This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, with the variations that the only legal time zone is GMT and the separators between the elements of the date must be dashes.

expires is an optional attribute. If not specified, the cookie will expire when the user's session ends.

 
domain=DOMAIN_NAME
When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. If there is a tail match, then the cookie will go through path matching to see if it should be sent. "Tail matching" means that domain attribute is matched against the tail of the fully qualified domain name of the host. A domain attribute of "me.com" would match host names "yes.me.com" as well as "yes.no.me.com".

Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL" and "INT". The default value of domain is the host name of the server which generated the cookie response.

 
path=PATH
The path attribute is used to specify the subset of URLs in a domain for which the cookie is valid. If a cookie has already passed domain matching, then the pathname component of the URL is compared with the path attribute, and if there is a match, the cookie is considered valid and is sent along with the URL request. The path "/" is the most general path. If the path is not specified, it as assumed to be the same path as the document being described by the header which contains the cookie.
 
secure
If a cookie is marked secure, it will only be transmitted if the communications channel with the host is a secure one. Currently this means that secure cookies will only be sent to HTTPS (HTTP over SSL) servers. If secure is not specified, a cookie is considered safe to be sent in the clear over unsecured channels.

Syntax of the Cookie HTTP Request Header

When requesting a URL from an HTTP server, the browser will match the URL against all cookies and if any of them match, a line containing the name/value pairs of all matching cookies will be included in the HTTP request.

Cookie: NAME1=OPAQUE_STRING1; NAME2=OPAQUE_STRING2 ...

Security

An HTTP Cookie cannot be used to get data from your hard drive, get your email address or steal sensitive information about your person. Early implementations of Java and JavaScript could allow people to do this but for the most part these security leaks have been plugged. But HTTP Cookie can be used to track where you travel over a particular site. This site tracking can be done without using cookies as well. You can disallow cookies with the latest browsers. Some database driven shopping sites and informational sites do need cookies to run.

Set cookies

The SetCookie function and the SetC functions are functions that define the cookie. They allow you to take user input from a form and convert it into 'cookie' format. This code is meant as an experimental base for you to work with.

1) Insert the following code in the

then copy!

2) You then insert the form code for sending the data to the SetCookie and SetC functions. Experiment with onChange, onClick, onFocus, onBlur depending on whether you are using a button, text box, radio or button.

then copy!

TO VIEW THE RESULTS OF THE COOKIE

3) Paste into your page where you want the cookie results to be displayed. The GetCookieVal function and the GetCookie function find the cookies you created and display them on the page.

then copy!

 

How to pull the cookie value from the GetCookieVal and GetCookie functions:

then copy!

 

EXPLAINED

SetCookie: save to a cookie

function setCookie (name, value, expires) {
if (!expires) expires = new Date();
document.cookie = name + "=" + escape (value) + 
<-- save cookie value
"; expires=" + expires.toGMTString() +  "; path=/";
<-- set expiration date and path
}        
                                                

If you want to save someone's first name (such as Peter) to a cookie called "_fname", this is what you would need:

 var expdate = new Date ();
 expdate.setTime (expdate.getTime() + (1000 * 60 * 60 * 24 * 31));
 setCookie ("_fname", "Peter", expdate);

This function gives the cookie an expiration date of one month. The one month is set by multiplying 1000 milliseconds by 60 seconds by 60 minutes by 24 hours by 31 days. If you want to save the cookie for a year change the 31 to a 365. All cookies must have an expiration date. If you specify no expiration date the cookie will last through the current browser session. When setCookie() is run, it creates a cookie called "_fname", sets the value of the cookie to "Peter" and sets the expiration date to 31 days.

Another simple example:

function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : ";
expires=" + expires.toGMTString());
}

getCookie: read from a cookie

function getCookie (name) {
var acookie = document.cookie; 
var fname = name + "=";
var clen = acookie.length;
var cbegin = 0;
while (bbegin < clen) {
var bbegin = bbegin + fname.length;
if (acookie.substring(cbegin, bbegin) == fname) { 
var bend = acookie.indexOf (";", bbegin);
if (bend == -1) vend = clen;
return unescape(acookie.substring(bbegin, vend));
}
bbegin = acookie.indexOf(" ", bbegin) + 1;
if (bbegin == 0) break;
}
return null;
}

This function searches through the cookie until it finds the cookie name that you specify. Then it finds the value of the cookie and returns it. To get the cookie that was saved with "Peter's" name in it, you use:

document.write(getCookie("_fname"));

This prints out the value of the "_fname" cookie, which was set to "Peter". If you wanted to print out the value of some other cookie, you would just use its name instead of "_fname". You can give the value of a cookie to a variable, allowing you to manipulate the values and create programs that can save and load information. You always need to include both functions: setCookie() and getCookie().

Another example of getCookie:

function getCookie(name){
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
return null;
}

DelCookie: delete data from a cookie

If you wish to erase a cookie, use this function.

function delCookie (fname) {
var expireNow = new Date();
document.cookie = name + "=" +
"; expires=Wed, 03-Jan-90 00:00:01 GMT" +  "; path=/";
}

or more simple:

function delCookie(name) {
document.cookie = name + "=; expires=Wed, 03-Jan-90 00:00:01 GMT" + "; path=/";
}

Retrieve function

Function to retrieve an element's value from a form:

function getValue(element) {
var value = getCookie(element.name);
if (value != null) element.value = value;

Save function

Function to save an element's value from a form:

function setValue(element) {
setCookie(element.name, element.value, exp);
}

Example of a form

 

 

Bookmarking - How and Where

Posted on 2008-Jan-12 at 10:04 in Web programming

There are more and more places on the Web where one can add bookmarks. We have shortlisted some of the main spots and include a list here of what to place on your Web page to have it easily bookmarked in these places. Simply replace the The_Page_URL, The_Page_Title, and The_Page_Description to reflect your data, and add one or more bookmark icons to your Web page.

SimplytheBest Bookmarks http://simplythebest.net/submitnews.php?url=The_Page_URL&title=The_Page_Title&descr=The_Page_description
Yahoo! bookmarks http://myweb2.search.yahoo.com/myresults/bookmarklet?u=The_Page_URL&t=The_Page_Title
Facebook bookmarks http://www.facebook.com/sharer.php?u=The_Page_URL&t=The_Page_Title
 Google bookmarks  http://www.google.com/bookmarks/mark?op=edit&bkmk=The_Page_URL&title=The_Page_Title
 Digg bookmarks  http://digg.com/submit?phase=2&url=The_Page_URL&title=The_Page_Title
 Del.icio.us bookmarks  http://del.icio.us/post?url=The_Page_URL&title=The_Page_Title
 Windows Live bookmarks  https://favorites.live.com/quickadd.aspx?url=The_Page_URL&title=The_Page_Title
 Slashdot bookmarks  http://slashdot.org/bookmark.pl?url=The_Page_URL&title=The_Page_Title
Squidoo bookmarks   http://www.squidoo.com/lensmaster/bookmark?The_Page_URL
 Newsvine bookmarks  http://www.newsvine.com/_wine/save?u=The_Page_URL&h=The_Page_Title
 Ask Jeeves bookmarks  http://myjeeves.ask.com/mysearch/BookmarkIt?v=1.2&t=webpages&url=The_Page_URL&title=The_Page_Title
 Stumbleupon bookmarks  http://www.stumbleupon.com/submit?url=The_Page_URL&title=The_Page_Title
 Reddit bookmarks  http://reddit.com/submit?url=The_Page_URL&title=The_Page_Title
 Netscape bookmarks  http://www.netscape.com/submit/?U=The_Page_URL&T=The_Page_Title
 Furl bookmarks  http://furl.net/storeIt.jsp?u=The_Page_URL&t=The_Page_Title
 Technorati bookmarks  http://www.technorati.com/faves?add=The_Page_URL

 

Javascript reference

Posted on 2007-Oct-24 at 04:22 in Web programming

SERVER-SIDE JAVASCRIPT 1.4 DOCUMENTATION

  • Server-Side JavaScript Guide
    This guide describes object-based scripting language for client and server applications. JavaScript lets you create applications that run over the Internet. Client applications run in a browser, such as Netscape Navigator, and server applications run on a server, such as Netscape Enterprise Server. Using JavaScript, you can create dynamic HTML pages that process user input and maintain persistent data using special objects, files and relational databases. From JavaScript you can instantiate Java objects and access their public methods and fields. From Java you can access JavaScript objects, properties and methods. Last Updated: September 1999.
    View PDF | Download HTML | Download PDF

SERVER-SIDE JAVASCRIPT 1.2 DOCUMENTATION

CORE JAVASCRIPT 1.4 DOCUMENTATION

The core language includes a basic set of objects, such as Array, Date, and Math, and a basic set of language elements, such as operators, control structures and statements. You can extend core JavaScript for a variety of purposes by supplementing it with additional objects.

 

AJAX Technology - An Introduction

Posted on 2007-Sep-17 at 03:23 in Web programming

About AJAX

AJAX is used to develop rich Web applications that dynamically update content using asynchronous JavaScript and XML, embedded into a HTML, PHP or other dynamic page, without having to refresh entire Web pages with each user click. It is a cross-platform technique that can be applied on most operating systems, computer architectures, and Web browsers. It is based on open standards such as JavaScript and XML with open source implementations of other technologies.

The JavaScript code is used to send requests to the server. Some processing is then required to handle the request, find the and/or store the data. The framework used always includes a JavaScript part, and sometimes a server side part in PHP, ASP, CFM or other scripting language.

Elements of Ajax include:

  • XHTML and CSS for the presentation
  • JavaScript for local processing
  • DOM to access data in the page or XML/XSLT elements read on the server
  • asynchronous data retrieval using the XMLHttpRequest class

Many Ajax frameworks and libraries rely solely upon JavaScript and contain no server components and therefore server technology dependencies. They use XML, JSON, or another textual data format. A JavaScript library is loaded with a simple tag:

This tag loads the "ascript" library into the page and it becomes usable to the browser. The .js file will hold the several components that are needed. Typically:

1. create a XMLHttpRequest or ActiveXObject object (see below browser compatibility).
2. send the request using the open method.
3. monitor the state of the request.
4. get the response.
5. use the response received in your Web page or application.

The XMLHttpRequest class

Attributes

readyState the code successively changes value from 0 to 4 for ready state.
0 = request is not initialized
1 = request has been set up
2 = request has been sent
3 = request is being processed
4 = request is completed
status the status of the HTTP request.
200 = no error
400  = bad request
401 = unauthorized
403 = forbidden
404  = not found
500  = internal server error
and so forth.
responseText holds the loaded data as a string of characters.
responseXml holds an XML loaded file, DOM method allows to extract data.
onreadystatechange property that takes a function as the value that is invoked when the readystatechange event is sent. For example:
myrequest.onreadystatechange = function() {
if (myrequest.readyState == 4 && myrequest.status == 200) {
var myresponse = myrequest.responseText;
} }

Methods

open (mode, url, boolean) mode= the request type, either GET or POST.
url= the location of the file, with/without a path.
boolean= true (asynchronous) / false (synchronous).
A username and a password may be added to the arguments.
send ("string") for POST commands, always null when a GET command is used.
Example:
myrequest.open("GET","mydata.php",true);
myrequest.send(null);

Browser compatibility

Internet Explorer uses an ActiveXObject, while other browsers use the built-in JavaScript object called XMLHttpRequest. This means you will always have to check which browser is being used. This is usually done using the try and catch functions.

try {
// your code
}
catch(e) {
// handle errors
}

Standard browser checking using try and catch:

try {
xmlHttp=new XMLHttpRequest();   // Firefox, Opera, Safari
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      // Internet Explorer 6+
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      // Internet Explorer 5+
}
catch (e) {
alert('Your browser is old');
}
}
}

Another method:

var myrequest;
if (window.XMLHttpRequest){  // Firefox, Safari, Opera
myrequest = new XMLHttpRequest();
}
else if (window.ActiveXObject){  // IE 5
myrequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.ActiveXObject){  // IE 6+
myrequest = new ActiveXObject("Msxml2.XMLHTTP");
}
else {  // Error for old browser
alert ('Your browser is too old!');
}

AJAX FRAMEWORKS & LIBRARIES

Extensive Ajax libraries and frameworks that greatly simplify the writing of Ajax applications can be found here: Ajax libraries.

PHP

Server side, the programmer may use PHP to process requests from the browser. PHP deals with the database, the data, page generation or parts of a page and publish or update the page with any return data to the XMLHttpRequest object. PHP 5 specifically, thanks to its SimpleXML class, is able to create XML files that can be returned to the object. All these tasks require many functions, and the good news is that many libraries and frameworks already exist for the would-be Ajax programmer.

Sajax is an open source tool to make Ajax programming easier, using PHP, Perl or Python functions via JavaScript without needing a browser refresh. Visit Sajax .

Xajax is an open source PHP class library that allows you to easily create Web based Ajax applications using HTML, CSS, JavaScript, and PHP. Applications developed with xajax can asynchronously call server-side PHP functions and update content without reloading the page. Visit xajax .

Cake PHP is a rapid development framework for PHP that uses commonly known design patterns like ActiveRecord, Association Data Mapping, Front Controller and MVC. It enables PHP users at all levels to rapidly develop robust web applications. Visit Cake PHP.

Saja is a lightweight, open-source AJAX scripting engine for PHP 4/5, with optional secured data transfer. It is designed for the fast creation of simple, secure, and maintainable Ajax applications, without having to write any JavaScript. Visit Saja.

Ajason is a PHP 5 library and JavaScript client for Ajax applications. Fetch data asynchronously and develop interactive GUI-like Web applications. Call PHP functions and object methods from JavaScript and exchange complex data types between client and server. Visit ajason

.NET frameworks

  • Microsoft Ajax Library (formerly ATLAS) is made of a client side part, the Microsoft AJAX Library, and a server side part, theASP.NET 2.0 Ajax Extensions. Includes a component library with graphical widgets, the ASP.NET Ajax Control Toolkit.
     
  • Ajax.NET Professional serializes (converts and stores) .NET data in the JSON format.

 ColdFusion frameworks

  • AjaxCFC is aAn object oriented framework that provides developers seamless integration between JavaScript and ColdFusion, with built-in security and debugging functions. Visit AjaxCFC.
     
  • CFAjax implements Ajax in such a way that ColdFusion method calls on the server get executed using JavaScript. Visit CFAjax.
     
  • JSMX, its API runs entirely on the client and has no server side components. Extended to support also ColdFusion, XML, JSON, and WDDX or JavaScript on the server side from JavaScript requests on the client side. Visit JSMX.

RESOURCES

Many Ajax applications and scripts can be downloaded from SimplytheBest Scripts.

 

Introduction to CSS cascading stylesheets

Posted on 2007-Sep-7 at 05:01 in Web programming

Cascading Style Sheets are a markup language for defining the format of web pages

CSS markup can be placed within a STYLE tag (usually in the document's HEAD) or in an external file. This makes it easy to modify the format of your web pages later without having to edit the HTML markup itself. This is referred to as "clean separation of format (CSS) and content (HTML or XML)."

Using Cascading Style Sheets will also improve your site's performance. If you formatted every paragraph on your page using the HTML markup above, the extra HTML markup would really increase the file's size and download time. By contrast, a single CSS rule can achieve the same effect of formatting every paragraph, no matter how few or many paragraphs are on the page. Also, if you place all of your site's formatting rules into a single shared style sheet file, the browser will download that file only once and reload it from the cache thereafter, further reducing download time.

Finally, CSS markup can be used to format both HTML pages and XML pages, so if you learn CSS markup, this skill will serve you well formatting web content in the future. HTML style sheets allow you to apply styles across a site or change the appearance of all your pages. They let you specify the appearance of a template page which is applied to all pages of a site. The goal of CSS is to provide a way of separating content from formatting. CSS allows you to put your title into a "H1" tag and define its font, size, color and more for all pages where it appears.

You can apply one stylesheet across multiple files by including a link to it in the of your document. Use stylesheets to control the position attributes of block-level elements on a page, or specify the exact attributes of any element on a page. Each element has its own set of attributes, and the appearance of everything inside the block-level elements is affected by those attributes. You can also nest block-level elements.

  • Use positioning carefully
  • When specifying text attributes, stick to font size and font face attributes

CSS standards

Tutorials about CSS

You can find a streaming audio presentation page at http://media.netscape.com/ including one streaming audio presentation on Introduction to Cascading Style Sheets (CSS1) and a second presentation on Introduction to Cascading Style Sheets Positioning (CSSP). The basic CSSP properties explained there are partially supported in Navigator 4 and Internet Explorer 4 and later and will be fully supported in IExplorer 5 and Navigator 5. These CSSP properties were originally defined in an interim specification called Positioning HTML Elements with Cascading Style Sheets which was released between the CSS1 and CSS2 specifications; they have since been incorporated into the CSS2 specification. WebReference CSS Tutorial, WebReview's articles on stylesheets

Which browsers support which CSS features?

Internet Explorer 3, 4, and 5, Navigator 4, and Opera all have partial support for Cascading Style Sheets, level 1. So when using Cascading Style Sheets you need to be conscious of which browsers implement which properties. Here are two reference tables:

Can I check my CSS markup to find mistakes?

 W3C CSS Validator will check your page, inform you of any markup errors and enable you to put a logo on your page if it is CSS-compliant.

A table of CSS properties and values is available at

http://blogs.simplythebest.net/RadianT/6/CSS+Properties.html.

 


Last Page | Page 1 of 2 | Next Page
RadianT's blog offers informational items, such as tips and tricks on many computer related subjects.

Links

- Home
- Archives
- RSS Feed