0% found this document useful (0 votes)
674 views

Chapter 3 Final

Html programming

Uploaded by

zemenemisganew5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
674 views

Chapter 3 Final

Html programming

Uploaded by

zemenemisganew5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Chapter 3

Client-Side Scripting Language


Internet Programming
Mr. Abel T.
Contents
Introduction

Client-Side Scripting Using JavaScript

Introduction to JavaScript

JavaScript Basics
Variables, Expression, Control Structure,
Array, Function
Event and Exception Handling

User Inputs: Form Processing


Cookies and Hidden Fields
Internet Programming 2 WU - KIoT- CS
JavaScript
 growth of the WWW has resulted in a demand for
dynamic and interactive web sites.
 There are many different kinds of scripting languages
– JavaScript, …
 JavaScript is a front-end scripting language
developed by Netscape for dynamic content
▪ can be used as object-oriented language
 Client-side technology
▪ Embedded in your HTML page
▪ Interpreted by the Web browser
 Simple and flexible
Internet Programming 3 WU - KIoT- CS
JavaScript Advantages
 JavaScript allows interactivity such as:
▪ Implementing form validation
▪ Enhancing user interactions
▪ React to user actions, e.g. handle keys
▪ Changing an image on moving mouse over it
▪ Sections of a page appearing and disappearing
▪ Content loading and changing dynamically
▪ Performing complex calculations
▪ Custom HTML controls, e.g. scrollable table
▪ Implementing AJAX functionality

Internet Programming 4 WU - KIoT- CS


Why Java Script?
 a web document can consist of up to three layers—
▪ content,
▪ presentation, and
▪ behavior

Internet Programming 5 WU - KIoT- CS


Content Layer
 content layer is always present
 It comprises the information the author wishes to
convey to his or her audience, and is embedded
within HTML or XHTML markup that defines its
structure and semantics
 Most of the content on the Web today is text, but
content can also be provided through images,
animations, sound, video, and whatever else an
author wants to publish.

Internet Programming 6 WU - KIoT- CS


Presentation Layer
 defines how the content will appear to a human
being who accesses the document in one way or
another
 The conventional way to view a web page is with a
regular web browser
▪ For example, content can also be converted to
synthetic speech for users who have impaired vision or
reading difficulties.

Internet Programming 7 WU - KIoT- CS


Behavior Layer
 The behavior layer involves real-time user
interaction with the document
 This task is normally handled by JavaScript
 The interaction can be anything from a validation
that ensures a required field is filled in before an
order form can be submitted,
 To sophisticated web applications that work much
like ordinary desktop programs

Internet Programming 8 WU - KIoT- CS


JavaScript and HTML page

<html> Tells where the JavaScript starts


<body>
<script type=“text/javascript”>
document.write(“Hello World!”);
</script>
</body> Commands for writing output to a page
</html>
Tells where the JavaScript ends

This code produce the output on an HTML page:


Hello World!

Internet Programming 9 WU - KIoT- CS


Cont’d

<html>
<head>
<script src="xyz.js"> </script>
</head>
<body> A separate file
</body>
</html>

Internet Programming 10 WU - KIoT- CS


JavaScript Syntax
 The JavaScript syntax is similar to C# and
Java
▪ Operators (+, *, =, !=, &&, ++, …)
▪ Variables (typeless)
▪ Conditional statements (if, else)
▪ Loops (for, while)
▪ Arrays (my_array[]) and associative arrays
(my_array['abc'])
▪ Functions (can return value)
▪ Function variables (like the C# delegates)

Internet Programming 11 WU - KIoT- CS


A Simple Script: Printing a Line of Text in
a Web Page
❑ Inline scripting
Written in the <body> of a document
❑<html>
<head> <title>First JavaScript Page</title> </head>
<script> tag
❑<body>
◦ Indicate
<h1>First that Page</h1>
JavaScript the text is part of a script
<script type="text/javascript">
◦ type attribute
<!--
 Specifies the type of file and the scripting language
document.write("<hr>"); use
document.write("Hello World Wide Web");
◦ writeln method
document.write("<hr>");
-->  Write a line in the document
◦ Escape character ( )
</script>
\
</body>
 Indicates “special” character is used in the string
</html>
◦ alert method
 Dialog box
Embedding JavaScript
<html>
<head>
<title>First JavaScript Program</title>
</head>
<body>
<script language=“JavaScript”
src=“your_source_file.js”></script>
</body>
</html>
 Embedding scripting
▪ A <script> tag can be placed either within the <head>
or <body> tag of an HTML document
Internet Programming 13 WU - KIoT- CS
JavaScript Source File: External
<script language=“JavaScript”
src=“your_source_file.js”></script>
▪ SRC – specifies the location of an external script
▪ TYPE – specifies the scripting language of the script
▪ LANGUAGE – specifies the scripting language of
the script
▪ TYPE and LANGUAGE have a similar function

Internet Programming 14 WU - KIoT- CS


Using the alert() Method
<head>
<script language=“JavaScript”>
alert(“An alert triggered by JavaScript”);
</script>
</head>
▪ It is the easiest methods to use amongst alert(),
prompt() and confirm().
▪ You can use it to display textual information to
the user (simple and concise).
▪ The user can simply click “OK” to close it.
Internet Programming 15 WU - KIoT- CS
Using the confirm() Method
<head>
<script language=“JavaScript”>
confirm(“Are you happy with the class?”);
</script>
</head>

▪ This box is used to give the user a choice either


OK or Cancel.
▪ It is very similar to the “alert()” method.
▪ You can also put your message in the method.

Internet Programming 16 WU - KIoT- CS


Using the alert() Method
<head>
<script language=“JavaScript”>
prompt(“What is your student id number?”);
prompt(“What is your name?”, ”No name”);
</script>
</head>
▪ This is the only one that allows the user to type
in his own response to the specific question.
▪ You can give a default value to avoid displaying
“undefined”.
Internet Programming 17 WU - KIoT- CS
Three methods
<script language="JavaScript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>

Internet Programming 18 WU - KIoT- CS


Variables
 JavaScript allows you to declare and use variables to
store values
 How to assign a name to a variable?
▪ Include uppercase and lowercase letters
▪ Digits from 0 through 9
▪ The underscore _ and the dollar sign $
▪ No space and punctuation characters
▪ First character must be alphabetic letter or underscore
– 99Total?, 012345number?, …
▪ Case-sensitive
▪ No reserved words or keywords

Internet Programming 19 WU - KIoT- CS


Which one is legal?
My_variable
Legal
$my_variable
1my_example
_my_variable
@my_variable
My_variable_example
++my_variable
%my_variable Illegal
#my_variable
~my_variable
myVariableExample

Internet Programming 20 WU - KIoT- CS


Variable on-the-fly
<head>
<script language=“JavaScript”>
Variable declaration
var id;
id = prompt(“What is your student id number?”);
alert(id);
name = prompt(“What is your name?”,”No name”);
alert(name);
</script>
</head>

▪ We should use “var” because it is more


easy to keep track of the variables
Internet Programming 21 WU - KIoT- CS
Data Types
 JavaScript allows the same variable to contain different
types of data values
 Primitive data types
▪ Number: integer & floating-point numbers
▪ Boolean: logical values “true” or “false”
▪ String: a sequence of alphanumeric characters
 Composite data types (or Complex data types)
▪ Object: a named collection of data
▪ Array: a sequence of values
 Special data types
▪ Null: an initial value is assigned
▪ Undefined: the variable has been created by not yet
assigned a value
Internet Programming 22 WU - KIoT- CS
Strings
 variable can store a sequence of alphanumeric characters,
spaces and special characters
 enclosed in single (‘) or in double quotation marks (“)
 What is the data type of “100”?
▪ String but not number type
<head>
<script language=“JavaScript”>
document.write(“This is a string.”);
document.write(“This string contains ‘quote’.”);
var myString = “My testing string”;
alert(myString);
</script>
</head>
Internet Programming 23 WU - KIoT- CS
What is an Object?
 object anything in the real world
o E.g. (cars, dogs, money, books, … )
 In web browser, objects are browser window itself,
forms, buttons, text boxes, …
 Methods are things that objects can do.
◦ Cars can move, dogs can bark
◦ Window object can alert the user “alert()”
 All objects have properties
◦ Cars have wheels, dogs have fur
◦ Browser has a name and version number

Internet Programming 24 WU - KIoT- CS


Array
 Array contains a set of data represented by a single
variable name
 Arrays in JavaScript are represented by the Array
Object, we need to “new Array()” to construct this
object
 The first element of the array is “Array[0]” until the
last one Array[i-1].
 E.g. myArray = new Array(5)
▪ We have myArray[0,1,2,3,4].

Internet Programming 25 WU - KIoT- CS


Array: example
<script language=“JavaScript”>
student = new Array(3);
student [0] = “Bekele”;
student[1] = “Lemma”;
student[2] = “Helen”;
document.write(student[0] + “<br>”);
document.write(student[1] + “<br>”);
document.write(student[2] + “<br>”);
</script>
▪ You can also declare arrays with variable length.
◦ arrayName = new Array();
◦ Length = 0, allows automatic extension of the length.
◦ Car[9] = “Ford”; Car[99] = “Honda”;
Internet Programming 26 WU - KIoT- CS
Null & Undefined
 An “undefined” value is returned when you attempt
to use a variable that has not been defined or you
have declared but you forgot to provide with a value
 Null refers to “nothing”
 You can declare and define a variable as “null” if you
want absolutely nothing in it, but you just don’t
want it to be “undefined”.

Internet Programming 27 WU - KIoT- CS


Null & Undefined example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“JavaScript”>
var test1, test2 = null;
alert(“No value assigned to the variable” + test1);
alert(“A null value was assigned” + test2);
</script>
</head>
<body> … </body>
</html>

Internet Programming 28 WU - KIoT- CS


Expressions
 It is a set of literals, variables, operators that merge
and evaluate to a single value
▪ Left_operand operator right_operand
 By using different operators, you can create the
following expressions.
▪ Arithmetic, logical
▪ String and conditional expressions.

Internet Programming 29 WU - KIoT- CS


Operators
 Arithmetic operators
 Logical operators
 Comparison operators
 String operators
 Bit-wise operators
 Assignment operators
 Conditional operators

Internet Programming 30 WU - KIoT- CS


Arithmetic Operators
 left_operand “operator” right_operand
Operator Name Description Example

+ Addition Adds the operands 3+5

- Subtraction Subtracts the right operand from 5-3


the left operand

* Multiplication Multiplies the operands 3*5

/ Division Divides the left operand by the 30 / 5


right operand

% Modulus Calculates the remainder 20 % 5

Internet Programming 31 WU - KIoT- CS


Unary Arithmetic Operators
 Binary operators take two operands
 Unary type operators take only one operand
 Which one add value first, and then assign value to
the variable?
Name Example

Post Incrementing operator Counter++

Post Decrementing operator Counter--

Pre Incrementing operator ++counter

Pre Decrementing operator --counter

Internet Programming 32 WU - KIoT- CS


Logical Operators
 Used to perform Boolean operations on Boolean
operands
Operator Name Description Example

&& Logical and Evaluate to “true” when both 3>2 && 5<2
operands are true

|| Logical or Evaluate to “true when either 3>1 || 2>5


operand is true

! Logical not Evaluate to “true” when the 5 != 3


operand is false

Internet Programming 33 WU - KIoT- CS


Comparison Operators
 Used to compare two numerical values
Operator Name Description Example

== Equal Perform type conversion before checking the “5” == 5


equality

=== Strictly equal No type conversion before testing “5” === 5

!= Not equal “true” when both operands are not equal 4 != 2

!== Strictly not equal No type conversion before testing nonequality 5 !== “5”

> Greater than “true” if left operand is greater than right operand 2>5

< Less than “true” if left operand is less than right operand 3<5

>= Greater than or “true” if left operand is greater than or equal to the 5 >= 2
equal right operand

<= Less than or “true” if left operand is less than or equal to the 5 <= 2
equal right operand
Internet Programming 34 WU - KIoT- CS
String Operators
▪ JavaScript only supports one string operator for
joining two strings.
Operator Name Description Return value
+ String Joins two strings “HelloWorld”
concatenation

<script language=“JavaScript”>
var myString = “”;
myString = “Hello” + “World”;
alert(myString);
</script>

Internet Programming 35 WU - KIoT- CS


Assignment Operators
 Used to assign values to variables
Operator Description Example

= Assigns the value of the right operand to the left operand A=2

+= Add the operands and assigns the result to the left A += 5


operand

-= Subtracts the operands and assigns the result to the left A -= 5


operand

*= Multiplies the operands and assigns the result to the left A *= 5


operand

/= Divides the left operands by the right operand and assigns A /= 5


the result to the left operand

%= Assigns the remainder to the left operand A %= 2

Internet Programming 36 WU - KIoT- CS


Order of Precedence
Precedence Operator
1 Parentheses, function calls
2 , ~, -, ++, --, new, void, delete
3 *, /, %
4 +, -
5 <<, >>, >>>
6 <, <=, >, >=
7 ==, !=, ===, !==
8 &
9 ^
10 |
11 &&
12 ||
13 ?:
14 =, +=, -=, *=, …
15 The comma (,) operator

Internet Programming 37 WU - KIoT- CS


Scope of Variable
 When you use a variable in a JavaScript program
that uses functions.
 global scope variable is one that is declared outside a
function and is accessible in any part of your program
 local variable is declared inside a function and stops
existing when the function ends

Internet Programming 38 WU - KIoT- CS


Conditional Statement
“if” statement
“if … else” statement
“else if” statement
“if/if … else” statement
“switch” statement

Internet Programming 39 WU - KIoT- CS


“if” Statement
if (condition) { statements; }

It is the main conditional statement in


JavaScript.
The keyword “if” always appears in lowercase.
The condition yields a logical true or false
value.
The condition is true, statements are
executed.
Internet Programming 40 WU - KIoT- CS
“if” Statement example
<script language=“JavaScript”>
var chr = “”;

if (chr == ‘A’ || chr == ‘O’) {
document.write(“Vowel variable”);
}
</script>

“||” operator - increase the speed of the script

Internet Programming 41 WU - KIoT- CS


“if…else” Statement
if (condition) { statements; }
else { statements; }
 You can include an “else” clause in if statement when you
want to execute some statements if the condition is false
<script language=“JavaScript”>
If (3 > 2) {
alert(“True”);
} else {
alert(“False”);
}
(3 > 2) ? alert(“True”) : alert(“False”);
</script>
Internet Programming 42 WU - KIoT- CS
“else if” Statement
if (condition) { statement; }
else if (condition) {
statement; }
else { statement; }
Allows you to test for multiple expression for
one true value and executes a particular block
of code.

Internet Programming 43 WU - KIoT- CS


“if/if…else” Statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Please enter a character : “,””);
if (chr >= ‘A’){
if (chr <= ‘Z’)
alert(“Uppercase”);
else if (chr >= ‘a’){
alert(“Lowercase”);
}
“||”
} operator - increase the speed of the script
</script>
Internet Programming 44 WU - KIoT- CS
“switch” Statement
switch (expression) {
case label1:
statements; break;
default:
statements;
}
Allows you to merge several evaluation tests
of the same variable into a single block of
statements.
Internet Programming 45 WU - KIoT- CS
“switch” Statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Pls enter a character in lowercase:”,””);
switch(chr){
case ‘a’ :
alert(“Vowel a”); break;
case ‘e’ :
alert(“Vowel e”); break;
default :
alert(“Not a vowel”);
}“||” operator - increase the speed of the script
</script>

Internet Programming 46 WU - KIoT- CS


Looping Statement
“for” Loops
“for/in” Loops
“while” Loops
“do … while” Loops
“break” statement
“continue” statement

Internet Programming 47 WU - KIoT- CS


“for” Statement
for (initial_expression; test_exp; change_exp)
{ statements; }

 One of the most used and familiar loops is the for


loop.
 It iterates through a sequence of statements for a
number of times controlled by a condition.
 The change_exp determines how much has been
added or subtracted from the counter variable.

Internet Programming 48 WU - KIoT- CS


“for” Statement example
<script language=“JavaScript”>
var counter;
for (counter = 1; counter <= 10; counter++)
{
document.write(counter*counter + “ “);
}
</script>

▪ Display the square of numbers


▪ Output: 1 4 9 16 25 36 49 64 81 100
Internet Programming 49 WU - KIoT- CS
“for/in” Statement
for (counter_variable in object)
{ statements; }

 When the for/in statement is used, the counter and


termination are determined by the length of the
object
 The statement begins with 0 as the initial value of
the counter variable, terminates with all the
properties of the objects have been exhausted.
▪ E.g. array → no more elements found

Internet Programming 50 WU - KIoT- CS


“for/in” Statement example
<script language=“JavaScript”>
var book; (What is the difference if “var
book=“”;)
var booklist = new Array(“Chinese”, “English”,
“Jap”);
for (var counter in booklist) {
book += booklist[counter] + “ “;
}
alert(book);
</script>

Internet Programming 51 WU - KIoT- CS


“while” Statement
initial value declaration;
while (condition) {
statements;
increment/decrement statement;
}

 while loop begins with a termination condition and


keeps looping until the termination condition is met.
 counter variable is managed by the context of the
statements inside the curly braces.

Internet Programming 52 WU - KIoT- CS


“while” Statement example
<html>
<head>
<title>While loop example</title>
<script language=“JavaScript”>
var counter = 100;
var numberlist = “”;
while (counter > 0) {
numberlist += “Number “ + counter + “<br>”;
counter -= 10;
}
document.write(numberlist);
</script> <body> … </body>
</html>
Internet Programming 53 WU - KIoT- CS
“do…while” Statement
do {
statements;
counter increment/decrement;
} while (termination condition)

 do/while loop always executes statements in the


loop in the first iteration of the loop
 termination condition is placed at the bottom of the
loop

Internet Programming 54 WU - KIoT- CS


Functions
 function is a block of organized reusable code (a set of
statements) for performing a single or related action
 contains some code that will be executed only by an
event or by a call to that function
 To keep the browser from executing a script as soon as the
page is loaded, you can write your script as a function
 can be defined either <head> or <body> section
 Begins with keyword “function” and function name
 Inside the parentheses
▪ We can pass parameters to the function
E.g. function myfuc(arg1, arg2) {…}
▪ Built-in and user-defined functions
Internet Programming 55 WU - KIoT- CS
Built-in Functions
 Functions provided by the language and you cannot
change them to suit your needs.
 Some of the built-in functions are shown here:
▪ eval - eval(expr)
• eval evaluates the expression or statements
▪ isFinite
• Determines if a number is finite
▪ isNaN
• Determines whether a value is “Not a Number”
▪ parseInt
• Converts string literals to integers, no number → NaN.
▪ parseFloat
• Finds a floating-point value at the beginning of a string.

Internet Programming 56 WU - KIoT- CS


User-Defined Functions
 For some functionality, you cannot achieve by only using
the built-in functions.
 You can define a function as follows
function <function_name> (parameters){
// code segments;
}
 Declaration Syntax
▪ return value is not declared, nor types of arguments
Examples: var number1=2, number2=4
calc(number1, number2); myFunction(number1, number2);
function calc(n1, n2) { function myFunction(a, b) {
return (n1 * n2); document.write(a * b);
} }
Internet Programming 57 WU - KIoT- CS
Events
 are actions that occur as a result of browser activities
or user interactions with the web pages, such as
▪ user performs an action (mouse click or enters data)
▪ validate the data entered by a user in a web form
▪ Communicate with Java applets and browser plug-ins
 Event categories
▪ Keyboard and mouse events
▪ Load events
▪ Form-related events
❑ onFocus() refers to placing the cursor into the text input
in the form.
▪ Others
❑ Errors, window resizing.
Internet Programming 58 WU - KIoT- CS
Events defined by JavaScript
HTML HTML JavaScript Description
defined events
elements tags
<a> click Mouse is clicked on a link
Link dblClick Mouse is double-clicked on a link
mouseDown Mouse button is pressed
mouseUp Mouse button is released
mouseOver Mouse is moved over a link
<img> load Image is loaded into a browser
Image abort Image loading is abandoned
error An error occurs during the image loading
<area> mouseOver mouse is moved over an image map area
Area mouseOut mouse is moved from image map to
dblClick outside
mouse is double-clicked on an image map
submit user submits a form
Form <form> Reset user refreshes a form
Internet Programming 59 WU - KIoT- CS
Event Handlers
 When an event occurs, a code segment is executed
in response to a specific event is called “event
handler”
 Event handler names are quite similar to the name
of events they handle
E.g event handler for the “click” event is “onClick”.
<HTMLtag eventhandler=“JavaScript Code”>

Internet Programming 60 WU - KIoT- CS


Cont’d
Event Handlers Triggered when
onChange The value of the text field, textarea, or a drop
down list is modified
onClick link, an image or a form element is clicked once
onDblClick The element is double-clicked
onMouseDown The user presses the mouse button
onLoad A document or an image is loaded
onSubmit A user submits a form
onReset The form is reset
onUnLoad The user closes a document or a frame
onResize A form is resized by the user
Internet Programming 61 WU - KIoT- CS
onClick Event Handlers
<html>
<head><title>onClick Event Handler Example</title>
<script language=“JavaScript”>
function warnUser(){
return confirm(“CSIT students?”);
}
</script>
</head>
<body>
<a href=“reference.html”, onClick=“return warnUser();”>CSIT
Students access only</a>
</body>
</html>

Internet Programming 62 WU - KIoT- CS


onLoad Event Handlers
<html>
<head>
<title>onLoad and onUnload Event Handler
Example</title>
</head>
<body onLoad=“alert(‘Welcome User’);”
onUnload=“alert(‘Thanks for visiting the page’);”>
Load and UnLoad event test.
</body>
</html>

Internet Programming 63 WU - KIoT- CS


User Events, Form Example
<html><head>
<title>Simple JavaScript Button</title>
<script language=“JavaScript"><!--
function dontClick() {
alert("I told you not to click!");
}
// --></script>
</head>
<body>
<h1>Simple JavaScript Button</h1>
<form>
<input type=“button“
value="Don't Click Me"
onClick="dontClick()">
</form></body></html>
Internet Programming 64 WU - KIoT- CS
Form Element-Based Objects
 HTML forms can include eight types of input
elements
▪ Text fields, Textarea fields
▪ Radio buttons
▪ Check box buttons
▪ Hidden fields
▪ Password fields
▪ Combo box select menu
▪ List select menu
▪ Each object has its own properties and methods.

Internet Programming 65 WU - KIoT- CS


Form Validation Script
<html><head> <body>
<title>Form Example</title>
<h1>Form Example</h1>
<script LANGUAGE="JavaScript">
function validate() { <p>Enter the following information. When
if (document.form1.yourname.value.length < you press the Display button, the data you
1) { entered will be validated, then sent by
alert("Please enter your full name."); email.</p>
return false;
} <form name="form1"
if (document.form1.address.value.length < 3) { action="mailto:[email protected]"
alert("Please enter your address."); enctype="text/plain“ onSubmit="validate();">
return false;
<p><b>Name:</b> <input type=“text"
}
length="20" name="yourname"></p>
if (document.form1.phone.value.length < 3) {
alert("Please enter your phone number."); <p><b>Address:</b> <input type=“text"
return false; length="30" name="address"></p>
} <p><b>Phone: </b> <input type=“text"
return true; length="15" name="phone"></p>
}
<p><input type=“submit" value="Submit"></p>
</script>
</head> </form></body></html>

Internet Programming 66 WU - KIoT- CS


Checking Form Values Individually Example
<html><head><title>On-Line Training</title>
<script language=“JavaScript">
<!--
// When the user changes and leaves textfield, check
// that a valid choice was entered. If not, alert
// user, clear field, and set focus back there.
function checkLanguage() {
// or document.forms["langForm"].elements["langField"]
var field = document.langForm.langField;
var lang = field.value;
var prefix = lang.substring(0, 4).toUpperCase();
if (prefix != "JAVA") {
alert("Sorry, '" + lang + "' is not valid.\n" +
"Please try again.");
field.value = ""; // Erase old value
field.focus(); // Give keyboard focus
}
}
Internet Programming 67 WU - KIoT- CS
Cont’d
// -->
</script></head>
<body><h1>On-Line Training</h1>
<form action="cgi-bin/registerLanguage" name="langForm">
To see an introduction to any of our on-line training courses,
please enter the name of an important Web programming language
below.
<p>
<b>Language:</b>
<input type=“text" name="langField"
onFocus="describeLanguage()" onBlur="clearStatus()"
onChange="checkLanguage()">
<p>
<input type=“submit" value="Show It To Me">
</form>
</body></html>
Internet Programming 68 WU - KIoT- CS
Result

Internet Programming 69 WU - KIoT- CS


When we need Cookies?
 The web servers process requests efficiently
because they did not need to maintain any unique
requirements for different clients
 Web browsers treat every visit to a web page as an
entirely new session, even if users open a different
web page on the same server.
 The client information becomes more important for
commercial purposes.

Internet Programming 70 WU - KIoT- CS


Cookie Basics
 When a user closes the browser, the information
contained in a hidden form field will be lost.
 A cookie is used to store information on the user’s
computer even when the user switches off his/her
computer.
 It is a data that is sent from a web server to a web
browser when the user visits a site on a server.
▪ It is just a .txt file in a user’s computer.

Internet Programming 71 WU - KIoT- CS


Features of Cookies
 A cookie can be associated with one or more
documents on the web server.
 More than one cookie can be associated with a
document on the web server.
 Every cookie has a NAME-VALUE pair associated
with it.
 Cookies have an expiration date associated with
them.

Internet Programming 72 WU - KIoT- CS


Cookies Applications
 Web page customization for each user
 Form information storage
 Shopping carts for order information
 Store userID and password
 Track how many times the user has visited
 Maintain a past score for each player on a test or
online games

Internet Programming 73 WU - KIoT- CS


Application: Using JavaScript to Store
and Examine Cookies
1. Using document.cookies
▪ Set it (one cookie at a time) to store values
document.cookie = "name1=val1";
document.cookie = "name2=val2; expires=" + someDate;
document.cookie = "name3=val3; path=/; domain=test.com";

▪ Read it (all cookies in a single string) to access values

Internet Programming 74 WU - KIoT- CS


Application: Using JavaScript to Store
and Examine Cookies
2. Parsing Cookies
function cookieVal(cookieName, cookieString) {
var startLoc = cookieString.indexOf(cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = cookieString.indexOf("=", startLoc);
var endLoc = cookieString.indexOf(";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = cookieString.length;
}
return(cookieString.substring(sepLoc+1, endLoc));
}
Internet Programming 75 WU - KIoT- CS
Thank You For your
Patience!

You might also like