SlideShare a Scribd company logo
1 of 28
Java Script Advance
BCA -302
2
Content
 JavaScript Cookies
 JavaScript Page Redirection
 JavaScript Document Object Model
 JavaScript Form Validation
 JavaScript Email Validation
 JavaScript Exceptional Handling
3
JavaScript Cookies
 A cookie is an amount of information that persists between a server-side and a client-
side. A web browser stores this information at the time of browsing.
 A cookie contains the information as a string generally in the form of a name-value
pair separated by semi-colons. It maintains the state of a user and remembers the
user's information among all the web pages.
 Cookies were originally designed for CGI programming. The data contained in a
cookie is automatically transmitted between the web browser and the web server, so
CGI scripts on the server can read and write cookie values that are stored on the
client.
 JavaScript can also manipulate cookies using the cookie property of
the Document object. JavaScript can read, create, modify, and delete the cookies
that apply to the current web page.
4
How Cookies Work?
 When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.
 So, to recognize the old user, we need to add the cookie with the response from the
server.
 browser at the client-side.
 Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users
5
Cookies
Cookies are a plain text data record of 5 variable-length fields −
1. Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.
2. Domain − The domain name of your site.
3. Path − The path to the directory or web page that set the cookie. This may be blank if you want
to retrieve the cookie from any directory or page.
4. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
5. Name=Value − Cookies are set and retrieved in the form of key-value pairs
Here the expires attribute is optional. If programmer provide this attribute with a valid date or time,
then the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason,
JavaScript escape() function is used to encode the value before storing it in the cookie and the
corresponding unescape() function is used to read the cookie value.
6
Syntax and Example of creating cookies
document.cookie = "key1 = value1;key2 = value2;expires = date";
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
7
Syntax and Example of creating cookies
document.cookie = "key1 = value1;key2 = value2;expires = date";
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
8
Example of creating cookies
9
JavaScript Page Redirection
There might be a situation where you clicked a URL to reach a page X but internally you were
directed to another page Y. It happens due to page redirection.
There could be various reasons why you would like to redirect a user from the original page. We are
listing down a few of the reasons −
 You did not like the name of your domain and you are moving to a new one. In such a scenario,
you may want to direct all your visitors to the new site. Here you can maintain your old domain but
put a single page with a page redirection such that all your old domain visitors can come to your
new domain.
 You have built-up various pages based on browser versions or their names or may be based on
different countries, then instead of using your server-side page redirection, you can use client-
side page redirection to land your users on the appropriate page.
 The Search Engines may have already indexed your pages. But while moving to another domain,
you would not like to lose your visitors coming through search engines. So you can use client-side
page redirection. But keep in mind this should not be done to fool the search engine, it could lead
your site to get banned.
10
Page Redirection Example
To redirect the page from one URL to another location() function is used:
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.ismp.ac.in";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>
</body>
</html>
11
JavaScript Document Object Model (DOM)
 The document object represents the whole html document.
 When html document is loaded in the browser, it becomes a document object.
 It is the root element that represents the html document.
 It has properties and methods.
 By the help of document object, we can add dynamic content to our web page
 The way a document content is accessed and modified is called the Document Object
Model, or DOM.
 The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document..
12
JavaScript Document Object Model (DOM)
 The document object represents the whole html document.
 When html document is loaded in the browser, it becomes a document object.
 It is the root element that represents the html document.
 It has properties and methods.
 By the help of document object, we can add dynamic content to our web page
 The way a document content is accessed and modified is called the Document Object
Model, or DOM.
 The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document..
13
JavaScript DOM Hierarchy
14
JavaScript DOM Methods
Method Description
write("string") writes the given string on the doucment.
writeln("string") writes the given string on the doucment with newline
character at the end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
15
JavaScript DOM Example
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
In the above code
document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
16
JavaScript getElementById() Example
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
17
JavaScript getElementsByName() Example
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Gend
ers">
</form>
18
JavaScript getElementsByTagName() Example
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by get
ElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
19
JavaScript innerHTML property Example
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows
='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
The innerHTML property can be used to write the dynamic html on the html document.
It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.
20
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation.
Most of the web developers prefer JavaScript form validation.
Programmer can validate a form by defining different function as per requirement. Common
validation include:
 Text Length
 Text Type
 Password Validation
 Email Validation, etc.
21
JavaScript Email Validation Example
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-
mail address n atpostion:"+atposition+"n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return valida
teemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
There are many criteria that
need to be follow to validate
the email id such as:
 email id must contain the
@ and . Character
 There must be at least
one character before and
after the @.
 There must be at least two
characters after . (dot).
22
JavaScript Form Validation Example
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
Following code will validate the name and password. The name can’t be empty and password can’t
be less than 6 characters long.
23
JavaScript Error and Exceptional Handling
 An exception signifies the presence of an abnormal condition which requires special
operable techniques. In programming terms, an exception is the anomalous code that
breaks the normal flow of the code. Such exceptions require specialized programming
constructs for its execution.
 In programming, exception handling is a process or method used for handling the abnormal
statements in the code and executing them.
 It also enables to handle the flow control of the code/program.
 For handling the code, various handlers are used that process the exception and execute
the code.
 For example, the Division of a non-zero value with zero will result into infinity always, and it
is an exception. Thus, with the help of exception handling, it can be executed and handled.
24
JavaScript Error and Exceptional Handling
While coding, there can be three types of errors in the code:
Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming
language, a syntax error may appear. It is also known as Parsing Error. When a syntax error
occurs in JavaScript, only the code contained within the same thread as the syntax error is
affected and the rest of the code in other threads gets executed assuming nothing in them
depends on the code containing the error.
Runtime Error: When an error occurs during the execution of the program, such an error is
known as Runtime error. The codes which create runtime errors are known as Exceptions.
Thus, exception handlers are used for handling runtime errors. Exceptions also affect the thread
in which they occur, allowing other JavaScript threads to continue normal execution.
Logical Error: An error which occurs when there is any logical mistake in the program that may
not produce the desired output, and may terminate abnormally. Such an error is known as
Logical error.
25
JavaScript Error and Exceptional Handling Contd…
There are following statements that handle if any exception occurs:
1. throw statements
2. try…catch statements
3. try…catch…finally statement
try{} statement: Here, the code which needs possible error testing is kept within the try block.
In case any error occur, it passes to the catch{} block for taking suitable actions and handle the
error. Otherwise, it executes the code written within.
catch{} statement: This block handles the error of the code by executing the set of statements
written within the block. This block contains either the user-defined exception handler or the
built-in handler. This block executes only when any error-prone code needs to be handled in the
try block. Otherwise, the catch block is skipped.
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and
the catch block is executed. The optional finally block executes unconditionally after try/catch.
26
Example of throw statement
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
</script>
</head>
<body>
<p>Click the following to see the
result:</p>
<form>
<input type = "button" value = "Click
Me" onclick = "myFunc();" />
</form>
</body>
</html>
27
Example of try-catch statement
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
</script>
</head>
<body>
<p>Click the following to see the
result:</p>
<form>
<input type = "button" value = "Click
Me" onclick = "myFunc();" />
</form>
</body>
</html>
28
Example of try…catch…finally statement
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always
execute!" );
}
}
</script>
</head>
<body>
<p>Click the following to see the
result:</p>
<form>
<input type = "button" value = "Click
Me" onclick = "myFunc();" />
</form>
</body>
</html>

More Related Content

What's hot (20)

1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
Web 5 | JavaScript Events
Web 5 | JavaScript EventsWeb 5 | JavaScript Events
Web 5 | JavaScript Events
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Web Development Introduction to jQuery
Web Development Introduction to jQueryWeb Development Introduction to jQuery
Web Development Introduction to jQuery
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
AngularJS By Vipin
AngularJS By VipinAngularJS By Vipin
AngularJS By Vipin
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
 
Javascript
Javascript Javascript
Javascript
 
Asp.net
Asp.netAsp.net
Asp.net
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
Java script cookies
Java script   cookiesJava script   cookies
Java script cookies
 
Javascript projects Course
Javascript projects CourseJavascript projects Course
Javascript projects Course
 
JavaScript Training
JavaScript TrainingJavaScript Training
JavaScript Training
 
03DOM.ppt
03DOM.ppt03DOM.ppt
03DOM.ppt
 
Managing states
Managing statesManaging states
Managing states
 
Intro to jQuery
Intro to jQueryIntro to jQuery
Intro to jQuery
 
Jquery Basics
Jquery BasicsJquery Basics
Jquery Basics
 
Java script
Java scriptJava script
Java script
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 

Similar to JavaScript Advance: Cookies, DOM, Validation

JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)WebStackAcademy
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptxVatsalJain39
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptxachutachut
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2Paras Mendiratta
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09Terry Yoast
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinSimon Gauvin
 
Java script Learn Easy
Java script Learn Easy Java script Learn Easy
Java script Learn Easy prince Loffar
 
Adding a view
Adding a viewAdding a view
Adding a viewNhan Do
 
Ch09 -Managing State and Information Security
Ch09 -Managing State and Information SecurityCh09 -Managing State and Information Security
Ch09 -Managing State and Information Securitydcomfort6819
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationSoumen Santra
 

Similar to JavaScript Advance: Cookies, DOM, Validation (20)

JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx
 
Java script
Java scriptJava script
Java script
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptx
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
 
Caching in asp.net
Caching in asp.netCaching in asp.net
Caching in asp.net
 
Caching in asp.net
Caching in asp.netCaching in asp.net
Caching in asp.net
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Angular js
Angular jsAngular js
Angular js
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
Java script Learn Easy
Java script Learn Easy Java script Learn Easy
Java script Learn Easy
 
Adding a view
Adding a viewAdding a view
Adding a view
 
Ch09 -Managing State and Information Security
Ch09 -Managing State and Information SecurityCh09 -Managing State and Information Security
Ch09 -Managing State and Information Security
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
 

More from Jaya Kumari

Python data type
Python data typePython data type
Python data typeJaya Kumari
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonJaya Kumari
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 
Basic syntax supported by python
Basic syntax supported by pythonBasic syntax supported by python
Basic syntax supported by pythonJaya Kumari
 
Decision statements
Decision statementsDecision statements
Decision statementsJaya Kumari
 
Loop control statements
Loop control statementsLoop control statements
Loop control statementsJaya Kumari
 
Looping statements
Looping statementsLooping statements
Looping statementsJaya Kumari
 
Operators used in vb.net
Operators used in vb.netOperators used in vb.net
Operators used in vb.netJaya Kumari
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NETJaya Kumari
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netJaya Kumari
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.netJaya Kumari
 
Frame class library and namespace
Frame class library and namespaceFrame class library and namespace
Frame class library and namespaceJaya Kumari
 
Introduction to .net
Introduction to .net Introduction to .net
Introduction to .net Jaya Kumari
 
Java script Basic
Java script BasicJava script Basic
Java script BasicJaya Kumari
 

More from Jaya Kumari (20)

Python data type
Python data typePython data type
Python data type
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Basic syntax supported by python
Basic syntax supported by pythonBasic syntax supported by python
Basic syntax supported by python
 
Oops
OopsOops
Oops
 
Inheritance
InheritanceInheritance
Inheritance
 
Overloading
OverloadingOverloading
Overloading
 
Decision statements
Decision statementsDecision statements
Decision statements
 
Loop control statements
Loop control statementsLoop control statements
Loop control statements
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Operators used in vb.net
Operators used in vb.netOperators used in vb.net
Operators used in vb.net
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Frame class library and namespace
Frame class library and namespaceFrame class library and namespace
Frame class library and namespace
 
Introduction to .net
Introduction to .net Introduction to .net
Introduction to .net
 
Jsp basic
Jsp basicJsp basic
Jsp basic
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
Sgml and xml
Sgml and xmlSgml and xml
Sgml and xml
 
Html form
Html formHtml form
Html form
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

JavaScript Advance: Cookies, DOM, Validation

  • 2. 2 Content  JavaScript Cookies  JavaScript Page Redirection  JavaScript Document Object Model  JavaScript Form Validation  JavaScript Email Validation  JavaScript Exceptional Handling
  • 3. 3 JavaScript Cookies  A cookie is an amount of information that persists between a server-side and a client- side. A web browser stores this information at the time of browsing.  A cookie contains the information as a string generally in the form of a name-value pair separated by semi-colons. It maintains the state of a user and remembers the user's information among all the web pages.  Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.  JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
  • 4. 4 How Cookies Work?  When a user sends a request to the server, then each of that request is treated as a new request sent by the different user.  So, to recognize the old user, we need to add the cookie with the response from the server.  browser at the client-side.  Now, whenever a user sends a request to the server, the cookie is added with that request automatically. Due to the cookie, the server recognizes the users
  • 5. 5 Cookies Cookies are a plain text data record of 5 variable-length fields − 1. Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. 2. Domain − The domain name of your site. 3. Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page. 4. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. 5. Name=Value − Cookies are set and retrieved in the form of key-value pairs Here the expires attribute is optional. If programmer provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible. Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, JavaScript escape() function is used to encode the value before storing it in the cookie and the corresponding unescape() function is used to read the cookie value.
  • 6. 6 Syntax and Example of creating cookies document.cookie = "key1 = value1;key2 = value2;expires = date"; <html> <head> <script type = "text/javascript"> function WriteCookie() { if( document.myform.customer.value == "" ) { alert("Enter some value!"); return; } cookievalue = escape(document.myform.customer.value) + ";"; document.cookie = "name=" + cookievalue; document.write ("Setting Cookies : " + "name=" + cookievalue ); } </script> </head> <body> <form name = "myform" action = ""> Enter name: <input type = "text" name = "customer"/> <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/> </form> </body> </html>
  • 7. 7 Syntax and Example of creating cookies document.cookie = "key1 = value1;key2 = value2;expires = date"; <html> <head> <script type = "text/javascript"> function WriteCookie() { if( document.myform.customer.value == "" ) { alert("Enter some value!"); return; } cookievalue = escape(document.myform.customer.value) + ";"; document.cookie = "name=" + cookievalue; document.write ("Setting Cookies : " + "name=" + cookievalue ); } </script> </head> <body> <form name = "myform" action = ""> Enter name: <input type = "text" name = "customer"/> <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/> </form> </body> </html>
  • 9. 9 JavaScript Page Redirection There might be a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons −  You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain.  You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client- side page redirection to land your users on the appropriate page.  The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned.
  • 10. 10 Page Redirection Example To redirect the page from one URL to another location() function is used: <html> <head> <script type = "text/javascript"> <!-- function Redirect() { window.location = "https://www.ismp.ac.in"; } //--> </script> </head> <body> <p>Click the following button, you will be redirected to home page.</p> <form> <input type = "button" value = "Redirect Me" onclick = "Redirect();" /> </form> </body> </html>
  • 11. 11 JavaScript Document Object Model (DOM)  The document object represents the whole html document.  When html document is loaded in the browser, it becomes a document object.  It is the root element that represents the html document.  It has properties and methods.  By the help of document object, we can add dynamic content to our web page  The way a document content is accessed and modified is called the Document Object Model, or DOM.  The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document..
  • 12. 12 JavaScript Document Object Model (DOM)  The document object represents the whole html document.  When html document is loaded in the browser, it becomes a document object.  It is the root element that represents the html document.  It has properties and methods.  By the help of document object, we can add dynamic content to our web page  The way a document content is accessed and modified is called the Document Object Model, or DOM.  The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document..
  • 14. 14 JavaScript DOM Methods Method Description write("string") writes the given string on the doucment. writeln("string") writes the given string on the doucment with newline character at the end. getElementById() returns the element having the given id value. getElementsByName() returns all the elements having the given name value. getElementsByTagName() returns all the elements having the given tag name. getElementsByClassName() returns all the elements having the given class name.
  • 15. 15 JavaScript DOM Example <script type="text/javascript"> function printvalue(){ var name=document.form1.name.value; alert("Welcome: "+name); } </script> <form name="form1"> Enter Name:<input type="text" name="name"/> <input type="button" onclick="printvalue()" value="print name"/> </form> In the above code document is the root element that represents the html document. form1 is the name of the form. name is the attribute name of the input text. value is the property, that returns the value of the input text.
  • 16. 16 JavaScript getElementById() Example <script type="text/javascript"> function getcube(){ var number=document.getElementById("number").value; alert(number*number*number); } </script> <form> Enter No:<input type="text" id="number" name="number"/><br/> <input type="button" value="cube" onclick="getcube()"/> </form>
  • 17. 17 JavaScript getElementsByName() Example <script type="text/javascript"> function totalelements() { var allgenders=document.getElementsByName("gender"); alert("Total Genders:"+allgenders.length); } </script> <form> Male:<input type="radio" name="gender" value="male"> Female:<input type="radio" name="gender" value="female"> <input type="button" onclick="totalelements()" value="Total Gend ers"> </form>
  • 18. 18 JavaScript getElementsByTagName() Example <script type="text/javascript"> function countpara(){ var totalpara=document.getElementsByTagName("p"); alert("total p tags are: "+totalpara.length); } </script> <p>This is a pragraph</p> <p>Here we are going to count total number of paragraphs by get ElementByTagName() method.</p> <p>Let's see the simple example</p> <button onclick="countpara()">count paragraph</button>
  • 19. 19 JavaScript innerHTML property Example <script type="text/javascript" > function showcommentform() { var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows ='5' cols='80'></textarea> <br><input type='submit' value='Post Comment'>"; document.getElementById('mylocation').innerHTML=data; } </script> <form name="myForm"> <input type="button" value="comment" onclick="showcommentform()"> <div id="mylocation"></div> </form> The innerHTML property can be used to write the dynamic html on the html document. It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.
  • 20. 20 JavaScript Form Validation It is important to validate the form submitted by the user because it can have inappropriate values. So, validation is must to authenticate user. JavaScript provides facility to validate the form on the client-side so data processing will be faster than server-side validation. Most of the web developers prefer JavaScript form validation. Programmer can validate a form by defining different function as per requirement. Common validation include:  Text Length  Text Type  Password Validation  Email Validation, etc.
  • 21. 21 JavaScript Email Validation Example <script> function validateemail() { var x=document.myform.email.value; var atposition=x.indexOf("@"); var dotposition=x.lastIndexOf("."); if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){ alert("Please enter a valid e- mail address n atpostion:"+atposition+"n dotposition:"+dotposition); return false; } } </script> <body> <form name="myform" method="post" action="#" onsubmit="return valida teemail();"> Email: <input type="text" name="email"><br/> <input type="submit" value="register"> </form> </body> </html> There are many criteria that need to be follow to validate the email id such as:  email id must contain the @ and . Character  There must be at least one character before and after the @.  There must be at least two characters after . (dot).
  • 22. 22 JavaScript Form Validation Example <script> function validateform(){ var name=document.myform.name.value; var password=document.myform.password.value; if (name==null || name==""){ alert("Name can't be blank"); return false; }else if(password.length<6){ alert("Password must be at least 6 characters long."); return false; } } </script> <body> <form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" > Name: <input type="text" name="name"><br/> Password: <input type="password" name="password"><br/> <input type="submit" value="register"> </form> Following code will validate the name and password. The name can’t be empty and password can’t be less than 6 characters long.
  • 23. 23 JavaScript Error and Exceptional Handling  An exception signifies the presence of an abnormal condition which requires special operable techniques. In programming terms, an exception is the anomalous code that breaks the normal flow of the code. Such exceptions require specialized programming constructs for its execution.  In programming, exception handling is a process or method used for handling the abnormal statements in the code and executing them.  It also enables to handle the flow control of the code/program.  For handling the code, various handlers are used that process the exception and execute the code.  For example, the Division of a non-zero value with zero will result into infinity always, and it is an exception. Thus, with the help of exception handling, it can be executed and handled.
  • 24. 24 JavaScript Error and Exceptional Handling While coding, there can be three types of errors in the code: Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language, a syntax error may appear. It is also known as Parsing Error. When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads gets executed assuming nothing in them depends on the code containing the error. Runtime Error: When an error occurs during the execution of the program, such an error is known as Runtime error. The codes which create runtime errors are known as Exceptions. Thus, exception handlers are used for handling runtime errors. Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution. Logical Error: An error which occurs when there is any logical mistake in the program that may not produce the desired output, and may terminate abnormally. Such an error is known as Logical error.
  • 25. 25 JavaScript Error and Exceptional Handling Contd… There are following statements that handle if any exception occurs: 1. throw statements 2. try…catch statements 3. try…catch…finally statement try{} statement: Here, the code which needs possible error testing is kept within the try block. In case any error occur, it passes to the catch{} block for taking suitable actions and handle the error. Otherwise, it executes the code written within. catch{} statement: This block handles the error of the code by executing the set of statements written within the block. This block contains either the user-defined exception handler or the built-in handler. This block executes only when any error-prone code needs to be handled in the try block. Otherwise, the catch block is skipped. The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.
  • 26. 26 Example of throw statement <html> <head> <script type = "text/javascript"> function myFunc() { var a = 100; var b = 0; try { if ( b == 0 ) { throw( "Divide by zero error." ); } else { var c = a / b; } } catch ( e ) { alert("Error: " + e ); } } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "myFunc();" /> </form> </body> </html>
  • 27. 27 Example of try-catch statement <html> <head> <script type = "text/javascript"> function myFunc() { var a = 100; try { alert("Value of variable a is : " + a ); } catch ( e ) { alert("Error: " + e.description ); } } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "myFunc();" /> </form> </body> </html>
  • 28. 28 Example of try…catch…finally statement <html> <head> <script type = "text/javascript"> function myFunc() { var a = 100; try { alert("Value of variable a is : " + a ); } catch ( e ) { alert("Error: " + e.description ); } finally { alert("Finally block will always execute!" ); } } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "myFunc();" /> </form> </body> </html>