Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
• Active Server Pages (ASP) is a server-side script that you can use to create interactive Web pages and build powerful Web applications.
• When the server receives a request for an ASP file, it processes server-side scripts contained in the file to build the Web page that is sent
to the browser.
• An ASP is a Web page that contains HTML code and embedded programming code written in VBScript or Jscript.
• When a browser requests an ASP file, IIS passes the request file to the ASP engine. The ASP engine reads the corresponding ASP file,
line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML format.
• ASP can connect to databases, dynamically format the page, execute statements, and much more. You may use VBScript, JavaScript,
within Active Server Pages, with VBScript set as the default scripting language.
What can ASP do for you?
• Dynamically edit, change or add any content of a Web page
• Respond to user queries or data submitted from HTML forms
• Access any data or databases and return the results to a browser
• Customize a Web page to make it more useful for individual users
• The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed
• Provide security since your ASP code can not be viewed from the browser
Working of ASP
• An ASP page is a Hypertext Markup Language (HTML) page that contains script commands that are processed by the Web server
before being sent to the client's browser. This explains how the term "server-side script" originated.
• When a Web client requests a static HTML file from a Web server, the Web server sends the HTML file directly to the client without
any computation being done The client's browser then processes the HTML code in the file and displays the content.
• VBScript is the simplest language for writing ASP pages. When a Web client requests an ASP file from a Web server, the Web server
sends the ASP file through its ASP engine, where all the server-side script code is executed or converted into HTML code The converted
code is then sent to the Web client.
<SCRIPT LANGUAGE=JAVASCRIPT>
…. JAVASCRIPT CODE GOES HERE ……
</SCRIPT>
Client side Javascript
<HTML><head><title>Client side (JAVA)scripting-Writing current datewith ASP</title></head>
<body bgcolor="cyan"><h2>Date Confirmation</h2>
<p>Today's Date is
<script language=JAVASCRIPT RUNAT=CLIENT>
d=new Date();
Document.Write(d);
</script> , and this ibvbs the first example of capter 2
</body></html
Client Side VBscript
<HTML><head><title>Client side (JAVA)scripting-Writing current datewith ASP</title></head>
<body bgcolor="cyan">
<h2>Date Confirmation</h2>
<p>Today's Date is
<script language=VBSCRIPT RUNAT=CLIENT>
Document.Write Date
</script> , and this ibvbs the first example of capter 2
</body></html>
Advantages and Disadvantages of Client side scripting
Advantages
– Create more functional. Interactive web pages
– Fast response
– Reduce server workload
– Network connection not required
Disadvantages
– Browser specific
– Code is completely visible to the user
– To keep secrete we need complex encryption techniques
Advantages and Disadvantages of Server side scripting
Advantages
– Create more functional. Interactive web pages
– Database facility
– Browser independent
– Code is completely un-visible to the user
Disadvantages
– Slow speed
– Need network connection
– Little bit complex program required
ASP Objects
Active Server Pages (ASP) implements classes that enable your component to access the properties and methods of the ASP built-in objects.
Your component can use these interfaces to access the methods and properties of the built-in objects. There are six important built-in objects to
provide additional functionality to your .asp files. The following are the six objects
• Request Object
• Response Object
• ObjectContext Object.
• Server Object
• Application Object
• Session Object
• ASPError Object
Request Object
You use the Request object to gain access to any information that is passed with an HTTP request. This includes parameters passed from an
HTML form using either the POST method or the GET method, cookies, and client certificates. The Request object also gives you access to
binary data sent to the server, such as file uploads.
Response Object
You use the Response object to control the information you send to a user. This includes sending information directly to the browser, redirecting
the browser to another URL, or setting cookie values.
Server Object
The Server object provides access to methods and properties on the server. The most frequently used method is the one that creates an instance of
an COM component (Server.CreateObject).
Other methods apply URL or HTML encoding to strings, map virtual paths to physical paths, and set the timeout period for a script.
Session Object
You use the Session object to store information needed for a particular user session. Variables stored in the Session object are not discarded when
the user jumps between pages in the application; instead, these variables persist for the entire time the user is accessing pages in your application.
You can also use Session methods to explicitly end a session and set the timeout period for an idle session.
ObjectContext Object
You use the ObjectContext object to either commit or abort a transaction initiated by an ASP script.
Application Object
It is used to represent the web application. You use the Application object to share information among all users of a given application.
ASPError Object
It contains detail of any error generated by an ASP script or by asp.dll itself.
Installing IIS
• Internet Information Services is not installed on Windows XP Professional by default. However, IIS 5.1 is installed by default only if
PWS was installed on your previous version of Windows.
• You can remove IIS or select additional components by using the Add/Remove Programs application in Control Panel.
1. Click Start, click Control Panel, and double-click Add/Remove Programs. The Add/Remove Programs application starts.
2. In the left column of the Add/Remove Programs dialog box, click Add/Remove Windows Components.
3. When the Windows Components Wizard appears, click Next.
4. In the Windows Components list, select IIS.
5. Click Next, and follow the instructions.
ASP Object
Methods Description
AddHeader Adds a header, which sends information about the page to the browser. This could be the location of the page, lang used,
server s/w etc.
AppendToLog Adds an entry to the server’s log file.
BinaryWrite Writes the given information to the current HTTP output without any character-set conversion.
Clear Clear any buffered html output. This can be used to clear invalid information entered by the user before displaying an error
page.
End Stop processing ASP page
Flush Send the content of the buffered to the browser and empty the buffer.
Redirect Redirect the user top different URL
Write Send data tot eh browser,
Properties Description
Buffer Specify whether the buffer the page output or not
Expires Sets how long (in minutes) a page will be cached on a browser before it expires
IsClientConnected Indicates of the client has disconnected from the server
Status Specify the value of the status line returned by the server
Collection Description
Cookies Sets a cookie value. If the cookie doesn't exist it will be created and take the value that is specified.
<html>body><pre>
<form action="responssum.asp">
Enter Number: <input type="test" Name="txtno">
<input type="Submit" value="Submit">
</form></pre></body></html>
REQUEST Object
Methods Description
Request.BinaryRead Retrieve binary data sent to the server
Properties Description
Request.TotalBytes Determine number of bytes sent in a request
Collection Description
Request.Cookies Retrieves information stored in a cookie on the client side
Requset.ClientCertificate Retrieves client certificates information
Request.Form Retrieves data posted by form
Request.QueryString Retrieves the values of variables passes by another page
Request.ServerVariables Retrieves the values of the variables stored on the server
Request.Form
You can see whether user completed the form or not using Request.Form. Also perform validation and access form elements in ASP
Sending data using POST method is invisible to others: see example below
<html>
<pre><body>
<form method=“POST" action="responssum.asp" name="abc">
Enter Number: <input type="test" Name="txtno"><br>
Enter Age: <input type="test" Name="age"><br>
Enter Adress: <input type="test" Name="add">
<input type="Submit" value="Submit">
</form>
</pre>
</body>
<html>
Request.QueryString
QueryString collection allow you to retrieve name and values of fields from a submitted form having name and value properties.
All form field stored in QueryString included submit button
Syntax for retrieving entire fields QueryString
Request.QueryString
Syntax for retrieving single field from QueryString
Request.QueryString(“FormFieldName”)
<html><pre><body>
<form method="Post" action="recdata.asp" name="abc">
Enter Number: <input type="test" Name="txtno"><br>
Enter Age: <input type="test" Name="age"><br>
Enter Adressr: <input type="test" Name="add">
<input type="Submit" value="Submit">
</form></pre></body><html>
<html><body>
You submitted the following inforamtion<br>
<% = Request.QueryString("txtno") %>
</body></html>
<html><body>
<form action="recdata1.asp" name="abc">
Enter First NAME: <input type="text" Name="txtfname"><br>
Enter Last Name : <input type="text" Name="txtlname"><br>
Enter EMAIL Adress: <input type="teXt" Name="eadd">
<input type="Submit" value="Submit">
</form></body></html>
<HTML><BODY>
<%
For Each formField in Request.QueryString
Response.write formField
Response.write " = "
Response.write Request.QueryString(formField)
Response.write "<BR>"
Next
%></BODY></HTML>
Server Object
The Server object provides access to methods and properties on the server. The most frequently used method is the one that creates an instance of
an COM component (Server.CreateObject)
Other methods apply URL or HTML encoding to strings, map virtual paths to physical paths, and set the timeout period for a script. Methods and
properties of server object are:
Properties Description
ScriptTimeout The amount of time that a script can run before it times out
Methods Description
CreateObject Creates an instance of server component
MapPath Maps the specified virtual path into physical path
URLEncode Applies URL encoding rules, including escape characters to the string
HTMLEncode Applies HTML to the specified string
<%= Server.HTMLEncode (“The Paragraph Tag: <p>”) %>
In source view :The Paragraph Tag: <p>
Server.MapPath(path)
Path parameter specifies relative or virtual path to a physical directory. If path start with “/” or “\” it return full virtual path. If not start then it
returns relative path of the .asp file processed.
Example:
Data Source= “&server.mappath("tickle.mdb")&”
Data Source=C:\Inetpub\wwwroot\database\tickle.mdb“
Data Source="&App.Path&"\tickle.mdb"
Session Object
You use the Session object to store information needed for a particular user session. Variables stored in the Session object are not
discarded when the user jumps between pages in the application; instead, these variables persist for the entire time the user is accessing
pages in your application. You can also use Session methods to explicitly end a session and set the timeout period for an idle session.
Session automatically expires after 20 minutes
Implemented using Cookie
Methods, Properties, Collection and Events
Methods Description
Session.Abandon End the session
Properties Description
Seesion.CodePage Specify the character-set used for the asp
Session.SessionID The unique identifier given by the server to each user
Sesion.Timeout Specify in minute how long session information stored on server
Collection Description
Session.Contents Contains items added to the session object using script
Session.StaticObject Contains items added to the session object using HTML <OBJECT> tag
Events Description
Session_OnStart Specifies an events to occur when the server creates a session
Session_OnEnd Specifies an events to occur when a session ends.
Following example set the session variables username to “Rahul” and the age to “50”
<html>
<body>
<%
Session(“UserName”)=“Rahul”
Session(“age”)=“50”
%>
</body>
</html>
When the value is created using session variables it can be reached to any ASP page
To remove all session variables
<% Session.Contents.RemoveAll()
To compare session variables
<% if Session.Contents(“age”)<18 then
Session.Contents.Remove(“sales”)
%>
Abandon Method
Session stop when the session timeout is reached OR
Some time user closes the browser and end the session. Some browser keep the session open even if the user is visiting another web site. To
force the browser to end the session used Abandon method.
The session is abandoned by calling the abandon of the session object. It stops the session gracefully; the ASP engine execute
Session_OnEnd subroutine before ending the session. Syntax is Session.Abandon
Application Object
• It is used to represent the web application. You use the Application object to share information among all users of a given
application.
• All user share one application object, while with session there is one session object for each user.
• The application object hold information that will be used by many pages in application means you can access information from
any page.
• It can also change information at one place and reflected on all pages.
Methods Description
Contents.Remove Deletes an item from the contents collection
Contents.RemoveAll() Deletes all items from the Contents collection
Application.Lock Prevents other users from modifying the variables in the application object
Application.Unlock Enables other users to modify he variables in application object
Collection Description
Application.Contents Contains items added to the application object using script
Application.StaticObject Contains items added to the application object using HTML <OBJECT> tag
Events Description
Application_OnStart Occur before the first new session is created
Application_OnEnd Occur when user sessions are over and application ends
ASPError Object
It contains detail of any error generated by an ASP script or by asp.dll itself.
Methods and Properties of Error Object are
Properties Description
Number Returns an integer value that uniquely identifies the error that occurred
Description Returns a description of a error
Source Returns the name of the object or method that caused error
HelpFile Returns the path and file name
Sets or return the ID for the help topic. Used to display help
Methods Description
Clear Clear out all the properties of the err object
Raise Generate an error for testing
Scripting Object
It is object can be used with both client side and server side script.
Two set of scripting object
– Scripting Runtime object (provided with II 5.0) and provide facility that was missed out from the VBScript and store in the file
scrrun.dll.
– VBScript object: It come as a part of VBScript and store in the file vbscript .dll. This file provides the scripting language
support to both ASP and IE.
Collectively these two object is known as Scripting Object.
– Comments:
• XML support you commenting with <!– and à
• You can place any tag bet these except for the double hyphen construct --.n These character sequence is reserved.
– Processing Instruction:
• Processing instruction (PI’s) enable you to embed information to be passed to an application
• All PIs have to follow syntax:
<?name data?>
– Ignored Section:
• Some time need to pass reserved character
• In these can you can define section that can be ignored by XML parser and directly passed to the processing
application
• Ex. Is passing < or > sign- A parser create character as parts of start and end tag. But if you put them in ignored
section like these
<! [CDATA[ 4 < 3 is FALSE. ]]>
• Ignored section start with <![CDATA[ and end with ]]>
Document Type Definition
If you share your document with other, XML parser may not be able to handle you document correctly.
So, you can share XML structure with it by writing DTD.
In DTD you specify your XML element, their attributes, and their syntax.
You can reference you DTD to top of your document so that XML parser knows where to find the DTD file.
DTD is a set of rules that specify how to used XML markup.
DTD contain, what the element is, what are the attributes and what values it can take.
You can define DTD in same file or in external files.
Valid and Well-formed XML documents
A document is said to be well-formed if
– It contains one or more elements
– The documents confirms the grammar put forward in the XML specification
– One element called the root elements. LETTER tag is the root element in above example
– All other non-empty elements are properly nested
– All attributes value are contained by quotation marks
IN absence of well-formed documents XML parser can build the document tree, but it can not access the proper use of the
element.
If it is not well-formed it is not XML and browser ignore it.
If a DTD is specified for a well-formed document and the document conforms the DTD the document is said to be valid.
The benefit of valid document is it is widely publishable. Every valid document have DTD and any XML parser can
processed this document.
Linking with XML
XML linking can be done with XML linking Language (XLink) and XML Pointer Language (XPointer).
Keeping extensible and flexible philosophy inherit in XML, XLink and XPointer call for more then the traditional
unidirectional link you get with HTML.
XML extend linking that allows multidirectional links or links to special kind of information.
XLink
Simple link:
Simple link are Uni-directional link from one source to another similar to how you use <A> in HTML.
Simple link is usually inline means that content of the element describing the link serve as a resource of the
link. You can specify you name.
E.g. <SIMPLINK>click </SIMPLINK>
ATTRIBUTES:
ACTUATE=“AUTO|USER”
It tell the processing application when the link should be traversed. In AUTO, link traversed when it is encountered, in USER, traversed
when user explicitly request.
BEHAVIOR
It provide more information how to carry out traversing.
CONTENT-ROLE: Describe the meaning of the content in the document you are linking to.
CONTENT-TITLE: Provide a title for the linked content that can be displayed to the user.
HREF: Specify the URL of the document.
INLINE=“TRUE|FLSE”: Says whether the link is inline. ROLE: Describe the meaning of Link.
SHOW=“EMBED|REPLACE|NEW”: It shows how to display the content with respect to the current content. EMBED: To embed the link
content inside the current content. REPLACE: Tells the application to overwrite the current content with the link content. NEW: Directs the
application to display the linked content in a new context.
TITLE: Provide the title for link.
XML:LINK: It is reserved to further standardization. Provide what kind of XML link the element support. Simple or Extended
For a simple link we can define DTD as follow:
<!Element simplelink>
<!ATTLIST simplelink
ACTUATE (AUTO|USER) “USER”
BEHAVIOR CDATA #IMPLIED
CONTENT ROLE CDATA #IMPLIED
CONTENT-ROLE CDATA #IMPLIED
HREF CDATA #REQUIRED
INLINE (TRUE|FALSE) “TRUE”
ROLE (REPLACE|EMBED|NEW)“REPLACE”
TITLE CDATA #IMPLIED
XML:LINK CDATA #FIXED “SIMPLE”
>
With this DTD you can specify a link as simple as:
<simplelink href=“link_doc.xml”>element</simplelink>
Extended Link
– It is differ from simple link in that they can point to any number of resources
– It is called “multilinked” it takes a user to many places.
– Two types of element are needed to specify extended link
• To contain the link text for each individual link resources <LOCATOR>
• To contains the elements that define the link resources. <EXTLINK>
The general extended link syntax
<EXTLINK>
<LOCATOR> Link Text </LOCATOR>
-- - - - - - - - - - - - -
<LOCATOR> Link Text </LOCATOR>
</EXTLINK>
All the attributes are same as simple link but it does not take HREF attribute because it contains the pointer to individual resources and
XML:LINK = EXTENDED. <LOCATOR> takes following attributes:
ACTUATE, BEHAVIOR, HREF, ROLE, SHOW, TITLE, XML:LINK
You should set XML:LINK = “LOCATOR”
Example:
<EXTLINK>
<LOCATOR XML:LINK=“LOCATOR” HREF=“URL1”>Click1 </LOCATOR>
<LOCATOR XML:LINK=“LOCATOR” HREF=“URL2”>Click2 </LOCATOR>
<LOCATOR XML:LINK=“LOCATOR” HREF=“URL3”>Click3 </LOCATOR>
CLICK
</EXTLINK>
This might take the pop-up menu with list of three options click1,click2 and click3. User can choose one of them.
XPoint (Extended Pointer or XPointer)
– It is called XML pointer Language or XPoint.
– It enable you to link to a position in a documents parsing tree
– It saved to from setting up named anchors the same as you do in HTML.
– In a business letter you could link to
Child(1,body) (3)
It refer the third child of the first BODY element in the letter.
Link can also point to span of document tree. E.g.
Child(3,p)..child(5,p)
Select third, fourth, and fifth <p> element. A pointer can span multiple element in the document tree called spanning tree.
Java Script Object Model
An object is a set of variables, functions, etc., that are in some way related. They are grouped together and given a name
Objects may have:
Properties
A variable (numeric, string or Boolean) associated with an object. Most properties can be changed by the user.
Example: the title of a document
Methods
Functions associated with an object. Can be called by the user.
Example: the alert() method
Events
Notification that a particular event has occurred. Can be used by the programmer to trigger responses.
Example: the onClick() event.
Java script interacts with browsers through browsers object model. It is as follows
The Window Object
Window is the fundamental object in the browser. It represents the browser window in which the document appears
Methods:-
alert(string):-Displays a message in a dialog box with an OK button.
confirm() :-Displays a message in a dialog box with OK and Cancel buttons. This returns true when the user clicks on OK, false otherwise.
close() :-Closes the current window.
eval(string):-Evaluates string and removes the value.
blur():- Removes focus from a window.
focus() :-Gives input focus to a window. In most versions of Navigator, this brings the window to the front
open(argument) :-Opens a new window with a specified document or opens the document in the specified named window.
prompt(string,default ) :-Displays a message in a dialog box along with a text entry field.
setTimeout(expression,msec) :-Sets a timer for a specified number of milliseconds and then evaluates an expression when the timer has finished
counting.
Two more methods of the window object enable you to set timeouts. These are statements (or groups of statements) that will be executed
after a certain amount of time elapses. These are handy for periodically updating a Web page or for delaying a message or function.
You begin a timeout with the setTimeout() method. This method has two parameters. The first is a JavaScript statement, or group of
statements, enclosed in quotes. The second parameter is the time to wait in milliseconds (thousandths of seconds). For example, this
statement displays an alert dialog after 10 seconds:
ident=window.setTimeout("alert('Time's up!')",10000); A variable (ident in this example) stores an identifier for the timeout. This
enables you to set multiple timeouts, each with its own identifier. Before a timeout has elapsed, you can stop it with the clearTimeout()
method, specifying the identifier of the timeout to stop:
window.clearTimeout(ident); These timeouts execute only once; they do not repeat unless you set another timeout each time.
Events:-
onLoad():- triggered when document is loaded into a window.
onUnload():- triggered when a document is closed or replaced with another document.
onBlur():- triggered when focus is removed from a window.
onFocus():- triggered when focus is applied on a window.
onError():- triggered when an error occurs.
Properties:-
defaultStatus:-The default value displayed in the status bar.
status :-The value of the text displayed in the window's status bar. This can be used to display status messages to the user.
Self:-The current window-use this to distinguish between windows and forms of the same name.
Top:-The top-most parent window.
parent :-The FRAMESET in a FRAMESET-FRAME relationship.
Opener:-Refers to the window containing the document that opened the current document.
Length:-number of frames in the current window.
frames :-Array of objects containing an entry for each child frame in a frameset document.
Opening and Closing Windows
By using the open() and close() methods, you have control over what windows are open and which documents they contain.
Syntax:-
window.open("URL", "windowName", "featureList");
Here the feature List is a comma-separated list containing any of the entries
Name Description
toolbar Creates the standard toolbar
location Creates the location entry field
directories Creates the standard directory buttons
status Creates the status bar
menubar Creates the menu at the top of the window
scrollbars Creates scroll bars when the document grows beyond the current window
resizable Enables resizing of the window by the user
Example:-
window.open("new.html","newWindow","toolbar=yes,
location=1, directories=yes, status=yes, menubar=1,
scrollbars=yes, resizable=0,width=200,
height=200");
The close() method is simpler to use:
Example:-
window.close();
simply closes the current window.
The location Object
The location object provides several properties and methods for working with the location of the current object.
Properties:-
Name Description
hash The anchor name (the text following a # symbol in an HREF attribute)
host Combination of the host name and port (www.starlingtech.com:80).
hostname The hostname of the URL. Specifies the host where the resource is located.
href whole URL, including all the parts listed
pathname The file path (the portion of the URL following the third slash)
port The port number of the URL. Specifies the Comm. port number on the host, usually 80 for the Web
protocol The protocol part of the URL (such as http:, gopher: or ftp:-including the colon)
Syntax:-
Window.location.property/method([parameter])
Example:-
Parent.location:-URL information of parent window
<FORM NAME="form1">
<INPUT TYPE="button" VALUE="< - BACK" onClick="history.back();">
...
<INPUT TYPE="button" VALUE="FORWARD - >" onClick="history.forward();">
The Date Object
The Date object provides mechanisms for working with dates and times in JavaScript. Instances of the object can be created as
Syntax:-
newObjectName = new Date()
Methods:-
ØgetDate() Returns the day of the month for the current Date object as an integer from 1 to 31. ØgetDay() Returns the day of the week
for the current Date object as an integer from 0 to 6 (where 0 is Sunday, 1 is Monday)ØgetHours() Returns the hour from the time in
the current Date object as an integer from 0 to 23. ØgetMinutes() Returns the minutes from the time in the current Date object as an
integer from 0 to 59. getMonth() Returns the month for the current Date object as an integer from 0 to 11 (where 0 is January, 1 is
February, etc.).
getSeconds() Returns the seconds from the time in the current Date object as an integer from 0 to 59.
getTime() Returns the time of the current Date object as an integer representing the number of milliseconds since January 1,
1970 at 00:00:00.
getYear() Returns the year for the current Date object as a two-digit integer representing the year minus 1900.
setDate(dateValue) Sets the day of the month for the current Date object. dateValue is an integer from 1 to 31.
setHours(hoursValue) Sets the hours for the time for the current Date object. hoursValue is an integer from 0 to 23.
setMinutes(minutesValue) Sets the minutes for the time for the current Date object. minutesValue is an integer from 0 to 59.
setMonth(monthValue) Sets the month for the current Date object. monthValue is an integer from 0 to 11 (where 0 is January, 1
is February, etc.).
setSeconds(secondsValue) Sets the seconds for the time for the current Date object. secondsValue is an integer from 0 to 59.
setTime(timeValue) Sets the value for the current Date object. timeValue is an integer representing the number of milliseconds
since January 1, 1970 at 00:00:00.
setYear(yearValue) Sets the year for the current Date object. yearValue is an integer greater than 1900.
The Math Object
The Math object provides properties and methods for advanced mathematical calculations.
Syntax to access properties & methods:-
Math.property
Math.method(value)
Name Description
LN10 The natural logarithm of 10 (roughly 2.302).
LN2 The natural logarithm of 2 (roughly 0.693).
PI The ratio of the circumference of a circle to the diameter of the same circle (roughly 3.1415).
SQRT1_2 The square root of 1/2 (roughly 0.707).
SQRT2 The square root of 2 (roughly 1.414).
abs() Calculates the absolute value of a number.
acos() Calculates the arc cosine of a number-returns result in radians.
asin() Calculates the arc sine of a number-returns result in radians
atan() Calculates the arc tangent of a number-returns result in radians
atan2() Calculates the angle of a polar coordinate that corresponds to a cartesian (x,y) coordinate passed to the method as arguments.
ceil() Returns the next integer greater than or equal to a number.
cos() Calculates the cosine of a number.
exp() Calculates e to the power of a number.
floor() Returns the next integer less than or equal to a number
log() Calculates the natural logarithm of a number.
max() Returns the greater of two numbers-takes two arguments.
min() Returns the least of two numbers-takes two arguments.
pow() Calculates the value of one number to the power of a second number-takes two arguments.
random() Returns a random number between zero and one.
round() Rounds a number to the nearest integer.
sin() Calculates the sine of a number.
sqrt() Calculates the square root of a number.
tan() Calculates the tangent of a number.
The Document Object
Another child of the window object is the document object. The Document object represents the HTML document displayed in a
browser window. It specify information about the current page.
Properties:-
alinkColor color of activated links
anchors Array of objects corresponding to each named anchor in a document
applets Array of objects corresponding to each Java applet included in a document
bgColor the background color as a hexadecimal triplet.
cookie Contains the value of the cookies for the current document.
fgColor The RGB value of the foreground color as a hexadecimal triplet.
forms Array of objects corresponding to each form in a document.
images Array of objects corresponding to each in-line image included in a document.
lastModified A string containing the last date the document was modified.
linkColor The RGB value of links as a hexadecimal triplet.
links An array of objects corresponding to each link in a document. Links can be hypertext links or clickable areas of an imagemap
The Form Object
When you create a form in an HTML document, you automatically create a form object with properties, methods and events that relate
to the form itself.
A separate instance of the form object is created for each form in a document.
A form object can be accessed or referred in two ways:-
Properties:-
Name:-The name of the form, as defined in the HTML <form> tag when the form is created
Example:- alert(document.forms[2].name);
Method:-The method used to submit the information in the form
Example:-alert(document.forms[2].method);
Action:-The action to be taken when the form is submitted
Example:-alert(document.forms[2].action);
Length:-The number of elements (text-boxes, buttons, etc.) in the form.
Example:-alert(document.forms[2].length);
element:-An array of all the elements in the form
Example:-alert(document.forms[2].elements[0].name);
will display the name of the first element in this form
Methods:-
Submit():-Submits the form data to the destination specified in the action attribute using the method specified in the method attribute.
this method invokes a click on the submit button of a form without invoking the onSubmit event handler.
Events:-
onSubmit:-Message sent each time a form is submitted. Can be used to trigger actions (e.g., calling a function). Usually placed within
the <form> tags, for example:
Example:-<form onSubmit="displayFarewell()">
would cause the function displayFarewell() to execute automatically every time the form is submitted.
Cookies
Netscape Developed the cookie as a means to store state-related and other information in persistent manner
This info in cookies maintained between browsers session
Cookies survives even user turn off the machine
Cookie information is shared between client browser and server using HTTP headers
When page is requested first time a cookie can be stored in the browser by a set-cookie entry in the header of the response from the
server.
Set-cookie fields include other optional information like expiry date, path, server information and security if required.
When used to maintain state, a date in the near future-typically the next day-is used. In the previous quiz example, a user that came back
the next day would have to start the quiz over.
The cookies are stored in a "cookie jar" on the user's computer. Specifically, each cookie is a line in a file called cookies.txt, usually in
the same directory as Netscape itself.
Here are some examples where cookies can be useful:
They can store a user's "preferences" for a Web page. When users return to the page, they can view it in their desired fashion. For
example, Netscape's home page uses this technique to turn frames on or off based on the user's preference.
They can maintain state between CGI scripts or JavaScript programs. For example, a quiz might ask you one question, then load a new
page for the next question, storing your score in a cookie.
They can remember information so that users can avoid entering it every time they access a page. For example, a page that requires a
user's name can remember it with a cookie.
Cookies can also be used in JavaScript. You can use them to store information between pages, or even to store information on users'
computers to remember their preferences next time they load your page.
When the user request a page in future, if a matching cookie is found among all the stored cookies, the browser sends a cookie field to
the server in a request header.
Set-cookie and cookie fields use a syntax to transfer significant information between client and server.
SETTING A COOKIE
Syntax:
set-cookie:NAME:value:EXPIRES=date;PATH=path; DOMAIN=domain;SECURE
NAME=Value is the only required field. Other are optional
Name Description
NAME=Value Specifies the name of the cookie
EXPIRS=Date Specify the expiry date of the cookie in DD-MMM-YY HH:MM:SS format. By default value of expires is end of current
session.
PATH=Path Specify the path portion of the URLs for which the cookie is valid. If the URL matches both the PATH and DOMAIN
then the cookie is sent to the server in the request header.
DOMAIN=Domain Specify the domain portion of the URL for which cookie is valid. The default value is the domain of the current
document.
SECURE Specify that the cookies should only be transmitted over a secure link
<html><head> </head>
<body>
<form name=f1>
<p> <font size=5> Enter a new Cookie
<Input type=text name=t1 size=60 value=""><p>
<input type="button" value="set cookie“ onClick="cook();">
</form>
<hr>
<script>
document.write("Your cookie value is "+ document.cookie);
document.cookie
</script>
</body>
</html>
<script>
function cook()
{
var dt=new Date()
document.cookie=document.f1.t1.value
expires=dt.getDate();
path="www.saintangelos.com"
domain="http://www.saintangelos.com"
secure="true"
document.f1.t1.value=document.cookie
}
</script>