Sei sulla pagina 1di 17

What Is ASP?

• 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.

Creating an ASP Page


An Active Server Pages (ASP) file is a text file with the extension .asp that contains any combination of the following:
1. Text
2. HTML tags
3. Server-side scripts
Adding Server-Side Script Commands
• A server-side script is a series of instructions used to sequentially issue commands to the Web server.
• ASP uses the delimiters <% and %> to enclose script commands. Within the delimiters, you can include any command that is valid for
the scripting language you are using.
• The following example shows a simple HTML page that contains a script command:
<HTML>
<BODY>
This page was last refreshed on <%= Now() %>.
</BODY>
</HTML>
The VBScript function Now() returns the current date and time. ’
Mixing HTML and Script Commands
• You can include, within ASP delimiters, any statement, expression, procedure, or operator that is valid for your primary scripting
language. The conditional If...Then...Else statement that appears below is a common VBScript statement:
<% Dim dtmHour
dtmHour = Hour(Now())
If dtmHour < 12 Then
strGreeting = "Good Morning!"
Else
strGreeting = "Hello!" End If %>
<%= strGreeting %>
Using ASP Directives
• ASP provides directives that are not part of the scripting language you use: the output directive and the processing directive.
• The ASP output directive <%= expression %> displays the value of an expression. This output directive is equivalent to using
Response.Write to display information. For example, the output expression <%= city %> displays the word Mumbai (the current value
of the variable) on the browser.
• The ASP processing directive <%@ keyword %> gives ASP the information it needs to process an .asp file. For example, the following
directive sets VBScript as the primary scripting language for the page:
• <%@ LANGUAGE=VBScript %> The processing directive must appear on the first line of an .asp file.

How Web server & browser Communicate


 When user tells browser for a page, the browser parcel up this instruction using protocol called the TCP.
 It provide a reliable transmission format.
 It ensures that entire message is correctly packaged up for transmission and also for unpacked properly at destination.
 Before that parcels of data they need to be addressed, so it is done by the HTTP (Internet protocol-IP). When HTTP used means internet
protocol is used.
 HTTP used by WWW in transfer of information from one m/c to another.
 IP control addressing and delivery, while TCP ensure that message is broken down, transported and reassembled correctly.
 The message passed from browser to web server is called HTTP request.
 When WS received a request from the WB, it check its store to find the appropriate page. If page is found, it sent to the browser using
TCP by using the address of HTTP. If page is not found, WS send a error page 404: Page Not Found (Is this case).
 The message sent from WS to WB is known as HTTP response.

Server side & client side script


 Server Side Script
– A script that is interpreted by the web server
– It is an instruction set that processed by the server, which generate HTML.
– The resulting HTML sent as part of the HTTP response to the browser
 Client Side Script
– A script that is interpreted by the web browser
– It is an instruction set that processed by the web browser, which generate HTML.
– The script is sent as part of the HTTP response to the browser
– Out put id displays by the browser
<HTML>
<head></head><body bgcolor="red">
<h2>Date Confermation</h2>
<p>Today's Date is
<script language=vbscript runat=server>
Response.write Date
</script> , and this is the first example of chapter 2
</body></html>
<HTML>
<head></head>
<body bgcolor="red">
<h2>Date Confermation</h2>
<p>Today's Date is
<% Response.write Date %>
, and this is the first example of chapter 2
</body></html>
Writing Client side scripting
<SCRIPT LANGUAGE=VBSCRIPT>
…. VBSCRIPT CODE GOES HERE ……
</SCRIPT>

<SCRIPT LANGUAGE=VBSCRIPT RUNAT=CLIENT>


…. VBSCRIPT CODE GOES HERE ……
</SCRIPT>

<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>

<% dim no,dig,no1,sum


no=Trim(Request.Form("txtno"))
sum=0
no1=no
Do While no <> 0
dig = no mod 10
sum = sum = dig
rev = (rev * 10) + dig
no=no \ 10
Loop
response.write "Sum= " & no1 & " is &nbsp; " & sum & "<BR>"
response.write "Reverse of digit entered is 7nbsp;" & rev %>

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 " &nbsp; = &nbsp;"
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: &lt;p&gt;

<% Response.write(Server.URLEncode("http://www.microsoft.com")) %>


In source view
http%3A%2F%2Fwww%2Emicrosoft%2Ecom

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

Creating and reading application variable


 The application variables are stored within the application object’s contents collection as an array of name and value pairs. To create an
application variable
Application.Contents.Item(“AppvariableName”)=NumericExpression
Application.Contents.Item(“AppvariableName”)=“StringExpression”
Application variables can access by using array index where index start with 1. Example
<% = Aplication.Contents.Item(1) %>
<% = Aplication.Contents(1) %> both are valid
 If you want to access the value of the application variables use
<% = application(“appName”)
dim strAppName
strAppName = application(“appName”) %>
Now strAppName can be used any where in the file.
The count properties gives the number of items in the application contents collection. It is used to through the entire collection contents. The
iteration must start with 1.
Total number of application variables is <%=application.Contents.Count %>
<% dim i

<% @ Language=VBScript %>


<% Application.Lock
if application("No_of_user")=" " then
application("No_of_user")=0
else
application("No_of_user")= application("No_of_user")+1
Application.Unlock
end if
%>
You are the <input type="text" value="<%=application("No_of_user") %>the visitor"><br>
You are the <input type="text" value="<%=application("No_of_user") %>the visitor"><br>
Total number of application variables is <%=application.Contents.Count %>

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

<% @ Language="VBScript" %>


<% Option Explicit %>
<% Response.write "Welcome to Error page"
On Error Resume Next
Dim myStrName
myStrName="Nurali Parkashan"
Response.write "Welcome !!!!" & myStName
if Err.Number > 0 then
Response.write "<BR><B>An Error Occured</b><BR>"
Response.write "Error Number : " & Err.Number
Response.write "<BR><B>Error Description :" & Err.Description
End if %>
<% @ Language="VBScript" %>
<% Option Explicit %>
<%
Response.write "Welcome to Error page"
On Error Resume Next
Response.write "Hello to Error"
Dim book(22)
book(23)="NURALI"

if Err.Number > 0 then


Response.write "<BR><B>An Error Occured</b><BR>"
Response.write "Error Number : " & Err.Number
Response.write "<BR><B>Error Description :" & Err.Description
End if
%>

Active Server Component


It is component or DLL. Following are the components provide by MS with IIS 5.0 and many more are available from third party.
 Ad Rotator Component: It is a rotator for ads that appear on the page. It is a list of images. It allow you to associate each image with a
separate hyperlink.
 Browser Capabilities Component: Reference a file called browscap.ini, which details every version of MS and Netscape browser.
 Content Linking Component: Uses a text file to manage a sequential set of web pages. It allow administrator to provide extra
information about each page in the sequence, and keep the links in an orderly list so that they can be easily maintained.
 Content Rotator Component: Same as Ad Rotator Component but used with only text.
 Counters Component: It create an object that persist for life time of application and can be store, increment and retrieve values.
 Logging Utility Component: It allow your application to read from your IIS log files which monitor who has been connecting to your
site.
 MyInfo Component: Used to store personal information about the server administrator
 Page Counter Component: It provide page counter which increment one each time page is accessed. It is automatic process not user
define.
 Permission Checker Component: Can be used to check whether a certain user has been given permission to read or execute a file.

Active Server Component


It is component or DLL. There are TEN components provide by MS with IIS 5.0 and many more are available from third party.
 Ad Rotator Component: It is a rotator for ads that appear on the page. It is a list of images. It allow you to associate each image with a
separate hyperlink.
 Browser Capabilities Component: Reference a file called browscap.ini, which details every version of MS and Netscape browser.
 Content Linking Component: Uses a text file to manage a sequential set of web pages. It allow administrator to provide extra
information about each page in the sequence, and keep the links in an orderly list so that they can be easily maintained.
 Content Rotator Component: Same as Ad Rotator Component but used with only text.
 Counters Component: It create an object that persist for life time of application and can be store, increment and retrieve values.
 Logging Utility Component: It allow your application to read from your IIS log files which monitor who has been connecting to your
site.
 MyInfo Component: Used to store personal information about the server administrator
 Page Counter Component: It provide page counter which increment one each time page is accessed. It is automatic process not user
define.
 Permission Checker Component: Can be used to check whether a certain user has been given permission to read or execute a file.
 Tools Component.

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.

Type of Scripting Object


Scripting Runtime object
 Dictionary Object: Allow you to store the information in a single data structure for easy retrieval like arrays.
 TextStream Object: It allow you to deal with the contents of a file that you have got information about using the FileSystemObject
object. You can read data from the file and can write to it.
 FileSystemObject: Allow access from an ASP script to the hard disk file system of the server. Allow you to work with files and
directories.
VBScript object:
 RegExp Object: It is a part of VBScript and can be used to manipulate a sequence of characters in a large amount of data.

Creating an Instance of Scripting Object


 Creating Scripting runtime object
set objDictionary = CreateObject (“Scripting.Dictionary”)

The FileSystemObject and It’s Object Model


 Object model is a group of related object which provide access to certain groups of function on the server. The FileSystemObject object
has the object model as follows:
– FileSystemObject
• Drive Collection
• Drive Object
– Folder Collection
– Folder Object
• Files Collection
• File Object
 The Drive Object
– It contains information regarding drive in the web server. Like as follows:
• Free space available
• The volume name of the drive
• An indication of whether or not the drive is ready
• The type of file system that that exist on the drive
• The physical type of the drive
• A reference to the root folder
– Most of the information in drive object is read only
– You can change the volume name, if it can physically be changed.

 The Drive Collection


– This contains one drive object for each of the drives on the system
– This includes all local drives, both fixed and removable and any network drive.
Method Name Purpose
GetDrive Returns a derive object from the drives collection; drive letter C: or a network share such as \\servename\sharename
GetDriveName Return name of the drive
 The Folder Object
– It allows you to access all the properties of the folder (includes name of the folder, collection of files within it, size of folder in
byte and attributes like read only, hidden, compressed, a system file of folder)
– If subfolder is there it also contain reference to it.
– You can copy, delete and move folder.
Method Name Purpose
GetFolder Returns a folder object from the folder collection
CreateFolder Create folder
CopyFolder Copy the folder from one location to another
MoveFolder Copy the folder from one location to another and delete the source folder
DeleteFolder Deletes a folder
FolderExists Determine whether a folder exists; Return true or False
File Object
• Lowest level object
• Allow access to all the properties of the individual file (it includes file name, path, reference to the folder object and size of the
file)
• You can copy, delete, move files
• The files Collection
• Contain all the file objects within a folder
• each files collection corresponds to a particular folder or sub-folder.

Method Name Purpose


GetFile Returns a file object from the file collection
FileExists Determine whether a file exists; Return true or False
CreateTextFile Creates a file and returns a TextStream object that is used to read from or write to a text file
CopyFile Copies the file from one location to another and delete the source folder
MoveFile Copies the file from one location to another and delete the source folder, You can delete by using DeleteFile methos
GetFileName Returns the name of the file. E.g. filename.txt
GetExtensionName Returns extension and
GetbaseName GetbaseName is used to get name of the file
XML
 HTML is a simple language
 HTML is a application of SGML, restricted to some rules
 HTML is focused on how contain should be presented rather than what the content
 Solution to these problem is XML
 XML stays focused on context description
 XML is highly extensible means that fl3xikble enough to handle simple document or huge document

Problem with HTML


 HTML tag describe how content should look on browser instead of saying what the content is
– E.g. <B., <I> <TT. <FONT>
 HTML is not flexible enough to properly markup wide variety of documents that people want to publish electronically.
 In html browser are so forgiving.

Problem with SGML


 SGML is so vast that it is overkill for most kind of web publication
 The SGML standard stretches on for pages and pages, making it more difficult for
– Content provider to markup content
– Programmer to write parser, browsers and other processing programs
– It has so many features which is difficult to remember
 XML is the advance version of SGML that drop some useless features and the result is the meta language. XML is
– Extensible: We can introduce tags into xml as appropriate to you publishing need.
– Portable:
– Structured
– Descriptive
Overview of XML
 Concept of XML includes:
– The different types of XML markup
– Document Type definition
– Valid XML document
– Well-formed XML document
 Types of XML markup
– Elements:
• Describe the meaning of text contain, occur in pairs with start tag and end tag,
• Empty tag written as <BR/>,
• Some elements takes attributes and must be enclosed by double quotation marks.
– Entities:
• It is similar to entities in HTML.
• In HTML you need entities to represent reserved character such as < or >. But in XML it is &lt; and &gt;
• You can define your own entities
• XML entities can also reside externally to the document.

– 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

The History Object


 The history object allows a script to work with the Navigator browser's history list in JavaScript.This object maintains the history list in
an array and individual items can be accessed through their indices.
 Example:-window.history[4]
Properties:-
 Next,current and previous:-next,current,and previous list in the list
 Length:- An integer representing the number of items on the history list
Methods:-
• back():- Goes back to the previous document in the history list.
• forward():- Goes forward to the next document in the history list.
• go(location):- Goes to the document in the history list specified by location. location can be a string or integer value. If it is a
string, it represents all or part of a URL in the history list. If it is an integer, location represents the relative position of the
document on the history list. As an integer, location can be positive or negative.

<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:-

1) Using position in the form array


Syntax:- document.forms[index]
Example:-document.forms[0]

2) Using name of the form


Syntax:- document.formname
Example:-document.form1
Accessing individual elements and their attributes:-
 All the controls used in a form are referred to as its element e.g: text,checkbox etc. the elements are referred in two ways:-
 By using array:-
Syntax:- document.form[index].element[index].attribute.
Example:- document.form[0].element[0].value.
 By using element name:-
Syntax:- document.formname.elementname.attribute.
Example:- document.form1. text1.value.

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>

Potrebbero piacerti anche