1
Web Technologies
IS2203
JavaScript(Validations)
Syllabus
Introduction: Web Development and Client Side Programming, Protocols Governing Web, Internet Services
and Tools, Client-Server Computing;
HTML: Basic Syntax, Standard HTML Document Structure, Basic Text Markup, Images, Hypertext Links, Lists,
Tables, Forms, HTML5;
CSS: Creating Style Sheets, Levels of Style Sheets, CSS Properties, Style Specification Formats, Selector Forms,
The Box Model, Conflict Resolution;
Javascript: Basics of Javascript, Variables, Arrays and Operators, Functions, Event Handlers, Built-in JS
Objects, Form Validations, Conditional and Loops, Local Storage and Cookies, Debugging and Testing;
Introduction to AJAX: AJAX and Node.Js Server, The Xmlhttprequest Object, Handling The Response, Jquery,
Passing Data, AJAX Application;
PHP Programming: Introduction to PHP, Creating PHP Script, Running PHP Script, Variables and Constants,
Data Types, Operators, Conditional Statements, Control Statements, Arrays, Functions, Working With Forms
and Databases Connection, Introduction to Web-Server and XAMPP.
2
Contents
• Introduction- HTTP Protocol
• Local Storage
• Session
• Cookies
3
4
Introduction- HTTP Protocol
HTTP is a “stateless” protocol
Treats each request for a web page as a unique and independent transaction
Does not maintain relationship to the transactions that preceded it.
Creates problem with transaction-based sites, which need to track the activities of each user.
5
Introduction- HTTP- Protocol
Consider, for example, the common shopping cart used in web storefronts:
In a “stateless” environment, it is impossible to keep track of the items each user has
short listed for purchase, as the stateless nature of the HTTP protocol makes it
impossible to identify which transactions belong to which client or user.
Consequently, a method is required is that makes it possible to “maintain state,”
something that allows client connections to be tracked and connection-specific data to
be maintained.
A common solution to the problem is to use sessions to store information about each
client and track its activities. This session data is preserved for the duration of the visit,
and is usually destroyed on its conclusion.
HTTP Request and Response
Step 1: Establishing a TCP connection to the server by the client
Step 2: Initiating a HTTP GET Request by the client to the server
A typical GET request looks like:
6
GET / HTTP/1.0
User-Agent: Wget/1.10.2 (Red Hat modified) Accept:
*/*
Host: 192.168.0.103
Connection: Keep-Alive
HTTP Request and Response
Step 3: HTTP Server Response to a HTTP GET Request as follows
7
HTTP/1.1 200 OK
Date: Tue, 31 Oct 2017 10:17:39 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 31 Oct 2017 10:17:39 GMT
ETag: "377709-6-f71984c0"
Accept-Ranges: bytes
Content-Length: 6
Connection: close
Content-Type: text/html; charset=UTF-8
hello
The Solution
Solutions are Session and Cookies
8
localStorage
• localStorage is part of the Web Storage API
• provides a way to store data locally within the user's browser
• Data stored using localStorage is persistent across browser sessions, i.e no expiration time
• localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared
when the last "private" tab is closed.
• keys and the values stored with localStorage are always in the UTF-16 string format (two bytes per
character)
• Integer keys are always converted to strings
localStorage.setItem(“myName”, “John”);
const name = localStorage.getItem(“myName”);
localStorage.removeItem(“myName");
localStorage.clear();
sessionStorage
• sessionStorage is similar to localStorage but with shorter lifecycle
• A session is created with each page opened in a tab
• Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window
• Duplicating a tab copies the tab's sessionStorage into the new tab
• page session lasts as long as the tab or the browser is open, and survives over page reloads and
restores
• data stored in sessionStorage is cleared when the page session ends (i.e., when the browser tab
is closed).
• sessionStorage creates different objects for different protocols (HTTP, HTTPS, FTP etc..)
// Save data to sessionStorage
sessionStorage.setItem("key", "value");
// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");
// Remove saved data from sessionStorage
sessionStorage.removeItem("key");
// Remove all saved data from sessionStorage
sessionStorage.clear();
sessionStorage
// Get the text field that we're going to track
let field = document.getElementById("field");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
// Restore the contents of the text field
field.value = sessionStorage.getItem("autosave");
}
// Listen for changes in the text field
field.addEventListener("change", () => {
// And save the results into the session storage object
sessionStorage.setItem("autosave", field.value);
});
12
Cookies
A cookie is a small piece of information that is retained on the client
machine, either in the browser’s application memory or as a small file
written to the user’s hard disk.
It contains a name/value pair—setting a cookie means associating a
value with a name and storing that pairing on the client side.
Getting or reading a cookie means using the name to retrieve the value.
Cookies
• A cookie is a small piece of information that is retained on the client machine, either in the
browser’s application memory or as a small file written to the user’s hard disk.
• An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a
user's web browser.
• Browser stores the cookie and sends it back to the same server with later requests
• Useful in identifying if two requests come from the same browser—keeping a user logged in
• remembers stateful information for the stateless HTTP protocol
• It contains a name/value pair—setting a cookie means associating a value with a name and
storing that pairing on the client side.
• Getting or reading a cookie means using the name to retrieve the value.
Cookies
• Client sends a HTTP request
• Server responds with one or more set-cookie headers data and n HTTP cookie
(web cookie, browser cookie) is a small piece of data that a server sends to a
user's web browser.
• browser stores the cookie and sends it with requests made to the same server
inside a Cookie HTTP header
Create a Cookie with JavaScript
To test cookies, enable:
• document.write(navigator.cookieEnabled);
JavaScript can create, read, and delete cookies with the document.cookie property.
document.cookie = ”username=glsaini”;
You can also add an expiry date (in UTC time). By default, the cookie is deleted when the
browser is closed:
Document.cookie = "username=glsaini; expires=Thu, 18 Dec 2030 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By
default, the cookie belongs to the current page.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC;
path=/";
We can create any number of cookies.
15
Read a Cookie with JavaScript
With JavaScript, cookies can be read like this:
let x = document.cookie;
document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value;
cookie3=value;
16
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it:
document.cookie = "username=John Smith; expires=Thu, 18 Dec 2024 12:00:00 UTC;
path=/";
The old cookie is overwritten.
17
Delete a Cookie with JavaScript
Just set the expires parameter to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Note:
You should define the cookie path to ensure that you delete the right cookie.
Some browsers will not let you delete a cookie if you don't specify the path.
18
A Function to Set a Cookie
function setCookie(name, value, days)
{
var expires = "";
if (days)
{
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
// document.cookie = name + "=" + (value || "") + expires + "; path=/";
document.cookie = `${name}=${value}; ${expires}; path=/`
}
19
A Function to Get a Cookie
function getCookie(name)
{
const cDecoded = decodeURIComponent(document.cookie);// it will store all cookie in
name value pair separated with ;
const cArray = cDecoded.split("; ");
//document.write(cArray);// display all cookies in the form of array
let result = null;
cArray.forEach(element =>
{
if(element.indexOf(name) == 0)
{
result = element.substring(name.length + 1)
}
})
return result;
}
20
A Function to delete a Cookie
function deleteCookie(name)
{
setCookie(name, null, null);
}
21
Time for Questions
22

19_JavaScript - Storage_Cookies-tutorial .pptx

  • 1.
  • 2.
    Syllabus Introduction: Web Developmentand Client Side Programming, Protocols Governing Web, Internet Services and Tools, Client-Server Computing; HTML: Basic Syntax, Standard HTML Document Structure, Basic Text Markup, Images, Hypertext Links, Lists, Tables, Forms, HTML5; CSS: Creating Style Sheets, Levels of Style Sheets, CSS Properties, Style Specification Formats, Selector Forms, The Box Model, Conflict Resolution; Javascript: Basics of Javascript, Variables, Arrays and Operators, Functions, Event Handlers, Built-in JS Objects, Form Validations, Conditional and Loops, Local Storage and Cookies, Debugging and Testing; Introduction to AJAX: AJAX and Node.Js Server, The Xmlhttprequest Object, Handling The Response, Jquery, Passing Data, AJAX Application; PHP Programming: Introduction to PHP, Creating PHP Script, Running PHP Script, Variables and Constants, Data Types, Operators, Conditional Statements, Control Statements, Arrays, Functions, Working With Forms and Databases Connection, Introduction to Web-Server and XAMPP. 2
  • 3.
    Contents • Introduction- HTTPProtocol • Local Storage • Session • Cookies 3
  • 4.
    4 Introduction- HTTP Protocol HTTPis a “stateless” protocol Treats each request for a web page as a unique and independent transaction Does not maintain relationship to the transactions that preceded it. Creates problem with transaction-based sites, which need to track the activities of each user.
  • 5.
    5 Introduction- HTTP- Protocol Consider,for example, the common shopping cart used in web storefronts: In a “stateless” environment, it is impossible to keep track of the items each user has short listed for purchase, as the stateless nature of the HTTP protocol makes it impossible to identify which transactions belong to which client or user. Consequently, a method is required is that makes it possible to “maintain state,” something that allows client connections to be tracked and connection-specific data to be maintained. A common solution to the problem is to use sessions to store information about each client and track its activities. This session data is preserved for the duration of the visit, and is usually destroyed on its conclusion.
  • 6.
    HTTP Request andResponse Step 1: Establishing a TCP connection to the server by the client Step 2: Initiating a HTTP GET Request by the client to the server A typical GET request looks like: 6 GET / HTTP/1.0 User-Agent: Wget/1.10.2 (Red Hat modified) Accept: */* Host: 192.168.0.103 Connection: Keep-Alive
  • 7.
    HTTP Request andResponse Step 3: HTTP Server Response to a HTTP GET Request as follows 7 HTTP/1.1 200 OK Date: Tue, 31 Oct 2017 10:17:39 GMT Server: Apache/2.2.3 (Red Hat) Last-Modified: Tue, 31 Oct 2017 10:17:39 GMT ETag: "377709-6-f71984c0" Accept-Ranges: bytes Content-Length: 6 Connection: close Content-Type: text/html; charset=UTF-8 hello
  • 8.
    The Solution Solutions areSession and Cookies 8
  • 9.
    localStorage • localStorage ispart of the Web Storage API • provides a way to store data locally within the user's browser • Data stored using localStorage is persistent across browser sessions, i.e no expiration time • localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed. • keys and the values stored with localStorage are always in the UTF-16 string format (two bytes per character) • Integer keys are always converted to strings localStorage.setItem(“myName”, “John”); const name = localStorage.getItem(“myName”); localStorage.removeItem(“myName"); localStorage.clear();
  • 10.
    sessionStorage • sessionStorage issimilar to localStorage but with shorter lifecycle • A session is created with each page opened in a tab • Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window • Duplicating a tab copies the tab's sessionStorage into the new tab • page session lasts as long as the tab or the browser is open, and survives over page reloads and restores • data stored in sessionStorage is cleared when the page session ends (i.e., when the browser tab is closed). • sessionStorage creates different objects for different protocols (HTTP, HTTPS, FTP etc..) // Save data to sessionStorage sessionStorage.setItem("key", "value"); // Get saved data from sessionStorage let data = sessionStorage.getItem("key"); // Remove saved data from sessionStorage sessionStorage.removeItem("key"); // Remove all saved data from sessionStorage sessionStorage.clear();
  • 11.
    sessionStorage // Get thetext field that we're going to track let field = document.getElementById("field"); // See if we have an autosave value // (this will only happen if the page is accidentally refreshed) if (sessionStorage.getItem("autosave")) { // Restore the contents of the text field field.value = sessionStorage.getItem("autosave"); } // Listen for changes in the text field field.addEventListener("change", () => { // And save the results into the session storage object sessionStorage.setItem("autosave", field.value); });
  • 12.
    12 Cookies A cookie isa small piece of information that is retained on the client machine, either in the browser’s application memory or as a small file written to the user’s hard disk. It contains a name/value pair—setting a cookie means associating a value with a name and storing that pairing on the client side. Getting or reading a cookie means using the name to retrieve the value.
  • 13.
    Cookies • A cookieis a small piece of information that is retained on the client machine, either in the browser’s application memory or as a small file written to the user’s hard disk. • An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. • Browser stores the cookie and sends it back to the same server with later requests • Useful in identifying if two requests come from the same browser—keeping a user logged in • remembers stateful information for the stateless HTTP protocol • It contains a name/value pair—setting a cookie means associating a value with a name and storing that pairing on the client side. • Getting or reading a cookie means using the name to retrieve the value.
  • 14.
    Cookies • Client sendsa HTTP request • Server responds with one or more set-cookie headers data and n HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. • browser stores the cookie and sends it with requests made to the same server inside a Cookie HTTP header
  • 15.
    Create a Cookiewith JavaScript To test cookies, enable: • document.write(navigator.cookieEnabled); JavaScript can create, read, and delete cookies with the document.cookie property. document.cookie = ”username=glsaini”; You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed: Document.cookie = "username=glsaini; expires=Thu, 18 Dec 2030 12:00:00 UTC"; With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page. document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/"; We can create any number of cookies. 15
  • 16.
    Read a Cookiewith JavaScript With JavaScript, cookies can be read like this: let x = document.cookie; document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value; 16
  • 17.
    Change a Cookiewith JavaScript With JavaScript, you can change a cookie the same way as you create it: document.cookie = "username=John Smith; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/"; The old cookie is overwritten. 17
  • 18.
    Delete a Cookiewith JavaScript Just set the expires parameter to a past date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; Note: You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don't specify the path. 18
  • 19.
    A Function toSet a Cookie function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } // document.cookie = name + "=" + (value || "") + expires + "; path=/"; document.cookie = `${name}=${value}; ${expires}; path=/` } 19
  • 20.
    A Function toGet a Cookie function getCookie(name) { const cDecoded = decodeURIComponent(document.cookie);// it will store all cookie in name value pair separated with ; const cArray = cDecoded.split("; "); //document.write(cArray);// display all cookies in the form of array let result = null; cArray.forEach(element => { if(element.indexOf(name) == 0) { result = element.substring(name.length + 1) } }) return result; } 20
  • 21.
    A Function todelete a Cookie function deleteCookie(name) { setCookie(name, null, null); } 21
  • 22.