Programming the Web using XHTML and JavaScript

Slides:



Advertisements
Similar presentations
CSCI 6962: Server-side Design and Programming Input Validation and Error Handling.
Advertisements

Cookies The HTTP protocol is stateless, that is, it does not maintain information on states after the session ends. But sometimes it is useful to remember.
Cookies Purpose –Write information that lives after the browser exits –Keep track of form data submitted multiple times during a particular visit –Track.
Lesson 8 Cookies. What is a cookie A little “tarball” of information stored on the client machine’s hard drive. –Usually in the cookies.txt file –information.
Web-based Application Development Lecture 20 April 4, 2006 Anita Raja.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
XP Tutorial 9 New Perspectives on JavaScript, Comprehensive1 Working with Cookies Managing Data in a Web Site Using JavaScript Cookies.
Web-based Application Development Lecture 19 March 23, 2006 Anita Raja.
CHAPTER 6 FILE PROCESSING. 2 Introduction  The most convenient way to process involving large data sets is to store them into a file for later processing.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
© 1999, by Que Education and Training, Chapter 5, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
Tutorial 14 Working with Forms and Regular Expressions.
Scripting Languages.
JavaScript, Fourth Edition
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Chapter 8 Cookies And Security JavaScript, Third Edition.
ASP.NET Programming with C# and SQL Server First Edition Chapter 5 Manipulating Strings with C#
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
Regular Expression (continue) and Cookies. Quick Review What letter values would be included for the following variable, which will be used for validation.
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
11 1 Cookies CGI/Perl Programming By Diane Zak Objectives In this chapter, you will: Learn the difference between temporary and persistent cookies.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
Persistence Maintaining state using cookies and queries.
Cookies (continue). Extracting Data From Cookies Data retrieved from a cookie is a simple text string. While there is no specific JavaScript function.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Cookies. Cookie A cookie is a method for a Web server to maintain state information about users as users navigate different pages on the site, and as.
IS2802 Introduction to Multimedia Applications for Business Lecture 8: JavaScript and Cookies Rob Gleasure
1 Project 7: Looping. Project 7 For this project you will produce two Java programs. The requirements for each program will be described separately on.
Project 5: Customizing User Content Essentials for Design JavaScript Level Two Michael Brooks.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
The purpose of a CPU is to process data Custom written software is created for a user to meet exact purpose Off the shelf software is developed by a software.
Session 2 Basics of PHP.
>> Fundamental Concepts in PHP
11 JavaScript: Objects.
CHAPTER 10 JAVA SCRIPT.
Excel STDEV.S Function.
CS 330 Class 7 Comments on Exam Programming plan for today:
Chapter 6 JavaScript: Introduction to Scripting
Strings CSCI 112: Programming in C.
© 2016 Pearson Education, Ltd. All rights reserved.
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
The Selection Structure
Programming the Web using XHTML and JavaScript
Introduction to Scripting
JavaScript Syntax and Semantics
Week#2 Day#1 Java Script Course
Working with Forms and Regular Expressions
Cookies and JavaScript
Advanced Programming Behnam Hatami Fall 2017.
Objectives Insert a script element Write JavaScript comments
BY: SITI NURBAYA ISMAIL FACULTY of COMPUTER and MATHEMATICAL SCIENCES
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
WEB PROGRAMMING JavaScript.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Programming in JavaScript
4.1 Strings ASCII & Processing Strings with the Functions
Programming in JavaScript
Chapter 3: Selection Structures: Making Decisions
Introduction to Computer Science
JavaScript: Introduction to Scripting
Chapter 17 JavaScript Arrays
Advanced Concepts and AJAX
Strings and Dates in JavaScript
Web Programming and Design
Chapter 8 JavaScript: Control Statements, Part 2
ASCII and Unicode.
Presentation transcript:

Programming the Web using XHTML and JavaScript Chapter 15 Strings, Dates, and Cookies

Introduction to strings

Validation and Verification

Validation vs. Verification Valid – meets certain criteria For example: a value is purely numeric a text value is no more than seven characters in length Verified – “represents the truth” User is allowed to access system User ID is defined to the system Password is correct a given User ID

Validation vs. Verification Verification is hard to accomplish “safely” with JavaScript Why? Two reasons ---

Verification Data and program to verify have to reside on the user’s computer  the list of UIDs and passwords Need to be downloaded to the user’s PC Takes time to download (and verify) Anyone can see!

Validation Validation accomplished easily in JavaScript Assume an input screen that requests: Name Must have at least an entry Student Identification Number (SID) Rules: Exactly eight digits Numerals only (no alphabetical characters)

Validation To validate the SID check: Remember Entry is exactly eight digits in length Each digit is in the range 0 to 9 only Remember Data input via a text box appears to JavaScript as a string String variables are actually string objects

Validation String objects possess: ~30 methods One property: For example: Search within the string for a substring Change the case of the string Replace one character in a string with another character One property: length (the number of characters in the string)

Validation Assume the form looks like this … Ch15-Ex-01

Validation Value stored in the SID text box is referred to as: document.surferInfo.SIDBox.value This is a string object so its length is referred to as: document.surferInfo.SIDBox.value.length Can validate its length with a conditional statement like this … Ch15-Ex-02

Starting character position Validation How can we check the individual string characters? String objects include a substring method Syntax (JavaScript) is substring(n,m) Starting character position Ending character position plus one, i.e. up to but not including this character

Validation Also, Thus, would result in char1 containing “B” var myName = “Bruce” var char1 = myName.substring(0,1) would result in char1 containing “B” Also, var char1 = myName.substring(2,4) would result in char1 containing “uc”

Validation In substring(n,m), the number of characters that are being referred to is: m – n So, substring(2,4) refers to 2 characters (4-2=2) Specifically the 3rd and 4th characters

Validation Just to confuse you: There is another substring function substr(s,l) Where: s: starting position (required) l: length (optional) To count back from the end of the string use a negative number for s If length is omitted the substring is taken to the end

Validation There is also a single character extraction function: charAt(n) That extracts the nth character: var myName = “Bruce” var char1 = myName.charAt(1) Results in char1 containing “r” Note that “extract” really means “copy”

Validation Handy Function: indexOf() Returns the first position of a character or string of characters If not found returns -1 First position is 0 Ch15-Ex-02a

Validation Collating sequence Computers represent everything as a numeric value Thus, every keyboard symbol has a value The ASCII code (used in PCs) defines the values for all symbols 7 bits – 128 values Extended uses 8 bits – 256 total values

ASCII Codes http://www.asciitable.com/

One of the extended ASCII Code pages

Validation Since every symbol has a value, a hierarchy can be established Thus, “A” is “less than” “B” because the ASCII code for an A (65) is less than the ASCII code for a B (66) “Z” (90) is less than “a” (97) Can use these relationships to see if a character in a string falls within a given range

Validation To validate the SID, we want to: Extract a single character Check to see that it’s a value in the numeric digit range (decimal values 48 – 57) Repeat until all characters have been checked

Validation Really means theChar=document.surferInfo.SIDBox.value.substring(0,1) if (theChar < "0" || theChar > "9") alert("Invalid SID") Really means If (the ASCII value of the character is less than 48 or the ASCII value of the character greater than 57) alert(“Invalid SID”)

Validation With a loop it is easy to repeat the process for each character in SIDBox: for (…) { theChar=document.surferInfo.SIDBox.value.substring(0,1) if (theChar<“0” || theChar>”9“) alert(“Invalid SID”) }

Validation Now we have to repeat this process for each character in SIDBox: for (i=0; i<=7; i++) { theChar=document.surferInfo.SIDBox.value.substring(0,1) if (theChar<“0” || theChar>”9“) alert(“Invalid SID”) }

Validation Need some way to control the loop and refer to subsequent characters in the substring: for (i=0; i<=7; i++) { theChar=document.surferInfo.SIDBox.value.substring(i,i+1) if (theChar<“0” || theChar>”9“) alert(“Invalid SID”) } Ch15-Ex-03

Validation Once we know the SID is invalid there’s no point in continuing the loop (Unless we want to painfully point out each invalid character individually) So, how to we stop a loop before it’s finished? With a break statement

Validation When JavaScript encounters break it acts like the continuing condition of the loop is false and immediately exits the loop Ch15-Ex-04

Date Objects

Date Objects JavaScript can access the computer’s date and time via a Date object Create a new one by: var timeandDate = new Date() Date objects include a number of methods

Date Objects Method Meaning Units getFullYear() 4-digit year 2000, 2001, etc. getMonth() Month no. 0-11 getDate() Day of month 1-31 getDay() Day of week 0-6 getHours() Hour no. 0-23 getMinutes() Minute no. 0-59 getSeconds() Second no.

Date Objects We can use Date objects to display the current date and time Ch15-Ex-05 What is the “problem”? Hint: there are two How can this be improved?

Cookies

Cookies Persistent data is data that exists over a long term Data created and manipulated in a JavaScript program ceases to exist when the containing Web page is changed Problem: How can we maintain data over a long period of time?

Cookies Why not write directly to the user’s hard drive? Security! Imagine if any Web page you accessed could write data/programs to your hard drive Instead …

Cookies Cookies String data stored in a special format May be long term persistent or temporary Small file (2,000 – 4,000 characters max.) Not more than a certain number from any one Internet domain (300 for Netscape) Create a cookie by assigning a string value to the cookie property of the document object

Cookies A cookie string consists of five parts in the following order: Cookie’s name and value Expiration date Pathname of the Web page creating the cookie Domain name of the server creating the cookie Security parameter to restrict access

Cookies For example, creating only the first part (name and value): document.cookie = “userName=Fred” Cookie Name Value Creates a cookie named userName whose value is Fred

Cookies Setting the expiration date requires storing two data items in the cookie: Name and value Expiration date Expiration date must be specified in Greenwich Mean Time (GMT) format

Cookies Browsers store time as the number of milliseconds (thousandths of a second) from January 1, 1970 to now When we create a new Date object, the browser sets its value to the number of milliseconds from 1/1/1970.

Cookies To change the value of a date object we need to add a certain number of milliseconds to it: Compute milliseconds Assign new value to the date object The getTime() method of a date object returns the current date in millisecond format Ch15-Ex-06

Cookies Now all we have to do is compute the number of milliseconds from now until the cookie should expire For a 30-day expiration that’s: 30 * 24 * 60 * 60 * 1000

Cookies To create an expiration date: var expDate = new Date() var currentDate = expDate.getTime() var thirtyDays = 30*24*60*60*1000 var fromNow = currentDate + thirtyDays

expDate.setTime(fromNow) Cookies Now set the date object to that value using the setTime method: expDate.setTime(fromNow) Ch15-Ex-07

Cookies More compactly: var expDate = new Date() expDate.setTime(expDate.getTime() + 30*24*60*60*1000)

Cookies JavaScript also provides: A setMonth() method to set month values directly … Ch15-Ex-08 As well as a toGMTString() method to convert date/time strings directly to GMT format

Cookies Once you’ve established a cookie’s expiration date you assign it to a cookie: var expDate = new Date() var currentMonth = expDate.getMonth() expDate.setMonth(currentMonth+1) document.cookie = "userName=Fred;expires=" + expDate.toGMTString()

Cookies However, JavaScript limited to reading only the “name=value” part of a cookie, not it’s expiration date How can you read the value of an existing cookie?

Cookies By using the string method named split() split() requires a parameter Used to parse a string into substrings at every location of the parameter

Cookies For example: var basicString = "alpha&beta&gamma" var thePieces = basicString.split("&") Creates an array of strings named thePieces such that: thePieces[0] = “alpha” thePieces[1] = “beta” thePieces[2] = “gamma” Ch15-Ex-09

Cookies How can we create multiple cookies? By assigning a new “name=value” to document.cookie But, there is only one document.cookie file? It can contain multiple “cookies”!

Cookies document.cookie=“userName=Fred” document.cookie=“password=George” It looks like the second statement replaces the first document.cookie However, there is only one cookie So what really happens is that the two values are appended together Ch15-Ex-10

Cookies To separate these into their constituent parts we execute a split twice Ch15-Ex-11

Extra Information Text Boxes: How to keep passwords private while typing them in PW:<input type='password' name='pw'> Ch15-Ex-12

Extra Information Upper or Lower Case? How to ease the problem? When validating information case matters! People out of habit may use capitalization, etc. Site may require all upper case A real pain to type How to ease the problem? toUpperCase() toLowerCase() Ch15-Ex-13

Assignment See Assignments Web Page Grade based on: Appearance Technical correctness of code Proper results