100% found this document useful (1 vote)
218 views

Chapter 3 - Client-Side Scripting Language

This document contains 5 pages about JavaScript. It begins by defining JavaScript as a dynamic programming language most commonly used in web pages to provide interactivity. It notes JavaScript's lightweight nature and object-oriented capabilities. The document then discusses JavaScript's use for client-side scripting to interact with users and dynamically generate HTML content. It provides examples of validating form data and manipulating HTML elements. The document also outlines some limitations of JavaScript and tools used for JavaScript development. It concludes by demonstrating basic JavaScript syntax like variables, expressions, control structures, and functions.

Uploaded by

Dafuq Malone
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
218 views

Chapter 3 - Client-Side Scripting Language

This document contains 5 pages about JavaScript. It begins by defining JavaScript as a dynamic programming language most commonly used in web pages to provide interactivity. It notes JavaScript's lightweight nature and object-oriented capabilities. The document then discusses JavaScript's use for client-side scripting to interact with users and dynamically generate HTML content. It provides examples of validating form data and manipulating HTML elements. The document also outlines some limitations of JavaScript and tools used for JavaScript development. It concludes by demonstrating basic JavaScript syntax like variables, expressions, control structures, and functions.

Uploaded by

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

Internet Programing 1

1
By Seiyfu Yesuf

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y.


Client-Side Scripting Language
2
2

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y.


What is JavaScript ?
 JavaScript is a dynamic computer programming language.
 It is lightweight and most commonly used as a part of web
pages, whose implementations allow client-side script to
interact with the user and make dynamic pages.
 It is an interpreted programming language with object-
oriented capabilities.
 Syntax is similar to Java, but it’s not Java.
 Usually JavaScript code is embedded within HTML code
using the script tag:
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 3
 Scripting language (object-oriented), lightweight
programming language, is a subset of java.
 Designed to be embedded in browsers, ideal for adding
interactivity to html pages
 Detect browser versions, work with info from user via
html forms
 Create cookies, validate form data
 Read and write html elements, it’s free, no license
required
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 4
 Client-side JavaScript is the most common form of the
language. The script should be included in or referenced by an
HTML document for the code to be interpreted by the browser.
 It means that a web page need not be a static HTML, but can
include programs that interact with the user, control the browser,
and dynamically create HTML content.
 The JavaScript client-side mechanism provides many
advantages over traditional server-side scripts.
 For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 5


 The JavaScript code is executed when the user submits the
form, and only if all the entries are valid, they would be submitted
to the Web Server.
 JavaScript can be used to trap user-initiated events such as
button clicks, link navigation, and other actions that the user
initiates explicitly or implicitly.
 Advantages of using JavaScript are:
 Less server interaction
 Immediate feedback to the visitors
 Increased interactivity
 Richer interfaces

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 6


Limitations of JavaScript
 It lacks the following important features −
 Client-side JavaScript does not allow the reading or writing of
files. This has been kept for security reason.
 JavaScript cannot be used for networking applications because
there is no such support available.
 JavaScript doesn't have any multi-threading or multiprocessor
capabilities.
JavaScript Development Tools
 Microsoft FrontPage − provides web developers with a number of JavaScript tools to
assist in the creation of interactive websites.
 Macromedia Dreamweaver MX − It provides several handy prebuilt JavaScript
components, integrates well with databases, and conforms to new standards such as
HTML and XML.
 Macromedia HomeSite 5 − used to manage personal websites effectively.
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 7
3.3.1 JavaScript Basics
 To include a JavaScript code in an HTML file, you must place the
code inside script tags and include the text/javascript type attribute
 All JavaScript statements end with a semicolon.
 The language is case sensitive.
 All variable names must begin with a letter or underscore.
 You can use comments to identify certain lines of your script. You
write comments using a double forward slash (//) followed by the
comment.
 You can also use comments to comment out script. A good way to
comment out multiple lines of script is by using /* your script goes
here */ Any script within the stars /* */ doesn’t run during execution.
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 8
 The script tags and type attribute are required to include JavaScript
code in an HTML file as shown in the example below:
 <script type="text/javascript"></script>
 To hide JavaScript code from browsers that do not support it, simply
use the comment tag before and after the JavaScript statement:
<script type="text/javascript">
<!--
Example statement here
-->
</script>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 9


 Helloworld example
<html>
<head><title>Helloworld in Java</title>
</head>
<body >
<p>Hello world from HTML</p>
<script type="text/javascript"> document.write("hello
world from Javascript")</script>
</body>
</html>
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 10
3.3.2 Variables ,Expression ,Control Structure ,Array , Functions
Variable Expression
 Variables are containers for storing data values that can later
be retrieved or updated with new data. The data stored in a
variable can be a value or expression.
 There are three types of expressions in the JavaScript
language:
 Arithmetic: Evaluates to a number. Example: 10 or 99
 String: Evaluates to a string. Example: “John” or “home”
 Logical: Evaluates to a Boolean (true or false). Example:
true or false, yes or no.
 Variables are declared with the var keyword. With the var
keyword.
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 11
 You have several options on structuring your variable
declaration and initialization:
// declaring one variable
var cost;
// declaring multiple variables, delimited by commas
var cost, profit;
// declaring and assigning one variable
var cost = 120;
// declaring and assigning multiple variables
var cost = 120, profit = 77;

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 12


Save as test.html
Save as script.js
<html> <script
type="text/javascript">
<head>
<script var num = 10;
src="Script.js"></script> document.write("The value
</head> of num is: "+ num);
<body </body> </script>
</html>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 13


 Control Structure: Conditional statements are the backbone
for creating any type of logic in a scripting or programming
language, and the JavaScript language is no exception.
 Conditional statements determine what action to take based on
the conditions you script.
 The four ways to write conditional statements in the JavaScript
language are:
 if: Used to execute a script if a specific condition is true.
 if...else: Used to decide which script to execute.
 if...else if...else: Adds more conditions.
 switch: It is an alternative to the if...else if...else statements.
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 14
 The following flow chart shows how the if-else statement
works.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 15


 Use if...else if...else to execute one script if one of the many if or
else if conditions is true, or the else script if all the conditions above it
are false.
 The code below checks to see if the value of x is positive, negative, or
zero.
var userinput=prompt(“input the number");
if (userinput > 0) {
document.write("number is positive");
} else if (userinput < 0) {
document.write("number is negative");
} else {
document.write("number is zero");
}
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 16
 Switch statements are different than the if statements. The
switch statements cannot use any conditions like the how the
if..else does.
 The objective of a switch statement is to give an expression to
evaluate and several different statements to execute based on
the value of the expression.
 The interpreter checks each case against the value of the
expression until a match is found. If nothing matches,
a default condition will be used.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 17


The following flow chart explains a var x = window.prompt(" enter a no.
switch-case statement works. less than 2");
x= Number(x)
switch (x)
{
case 0: document.write("zero") ;
break ;
case 1: document.write("one") ;
break ;
default: document.write("not
valid")
}

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 18


 An array is an ordered collection of
values referenced by a single variable var colors = new Array("orange",
name "blue", "red", "brown");
var variable = new document.write("Orange: "+
Array(size); colors[0]);
Where variable is the name of the document.write("Blue: "+ colors[1]);
array variable and document.write("Red: "+ colors[2]);
size is the number of elements in the document.write("Brown: "+
array colors[3]);
 It is also possible to assign a value to a
position in an array or update an item’s
value in an array, just as you accessed
an item in an
ASU/Computing/Computer array earlier.
Scienc Internet Programing/2019 by Seiyfu Y. 19
 A function is a group of reusable code which can be called anywhere
in your program. This eliminates the need of writing the same code
again and again.
 It helps programmers in writing modular codes. Functions allow a
programmer to divide a big program into a number of small and
manageable functions.
 Before we use a function, we need to define it. The most common way
to define a function in JavaScript is by using the function keyword,
followed by a unique function name, a list of parameters, and a
statement block surrounded by curly braces.
function functionname(parameter-list) {
statements }
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 20
 There is a facility to pass different parameters while calling a function.
 These passed parameters can be captured inside the function and any
manipulation can be done over those parameters.
 Functions can have one or more parameters, and a function call can
have one or more arguments based on the number of function
parameters.
 It is common to confuse parameters and arguments; parameters are part
of the function definition, and arguments are expressions used when
calling the function.
 A JavaScript function can have an optional return statement. This is
required if you want to return a value from a function.
 This statement should be the last statement in a function.
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 21
<html>
<head> <body>
<script type = "text/javascript">
function sayHello() { <p>text from the web
alert (" this generated by a function"); page</p>
}
function addone(thenumber){ <script type =
thenumber++; "text/javascript">
alert(thenumber);
} sayHello();
function multiplythis(thenumber,
anothernumber){ addone(100);
var
finalnum=thenumber*anothernumber; multiplythis(5,8);
alert(finalnum);
}
</script>
</script> </body>
</head>
</html>
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 22
3.3.3 Events and Exception Handling
 There are three types of errors in programming: (a) Syntax Errors, (b)
Runtime Errors, and (c) Logical Errors.
Syntax Errors
 Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
 The following line causes a syntax error because it is missing a closing
parenthesis.
document.write(;

Runtime Errors
 Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 23
 The following line causes a runtime error because here the
syntax is correct, but at runtime, it is trying to call a method that
does not exist.
window.printme();
Logical Errors
 Logic errors can be the most difficult type of errors to track down. These
errors are not the result of a syntax or runtime error.
 Instead, they occur when you make a mistake in the logic that drives your
script and you do not get the result you expected.
 You cannot catch those errors, because it depends on your business
requirement what type of logic you want to put in your program.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 24


 JavaScript implements the try...catch...finally construct as well as
the throw operator to handle exceptions.
 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.
 In the next slide is an example where we are trying to call a non-
existing function which in turn is raising an exception.
 Let us see how it behaves without try...catch

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 25


<html> <body>
<head> <p>Click the following to see
<script type = "text/javascript">
the result:</p>
function myFunc() { <form>
var a = 100; <input type = "button"
alert("Value of variable a is : "
value = "Click Me" onclick =
+ a ); "myFunc();" />
} </form>
</script> </body>
</head> </html>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 26


Now let us try to catch this exception using try...catch and display a
user-friendly message. You can also suppress this message, if you
want to hide this error from a user.

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!" );
} }

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 27


 You can use throw statement to raise your built-in exceptions
or your customized exceptions.
 Later these exceptions can be captured and you can take an
appropriate action.
 The following example demonstrates how to use
a throw statement.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 28


<head> <script type = "text/javascript"> <body>
function myFunc() { <p>Click the following to
var a = 100; see the result:</p>
var b = 0;
try { <form>
if ( b == 0 ) { <input type = "button"
value = "Click Me" onclick =
throw( "Divide by zero error." );
"myFunc();" />
} else {
</form>
var c = a / b; } }
</body>
catch ( e ) {
alert("Error: " + e );
} }
</script>
</head>
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 29
 Now follow these steps to build an anchor link:
 Form validation normally used to occur at the server, after the
client had entered all the necessary data and then pressed the
Submit button.
 If the data entered by a client was incorrect or was simply
missing, the server would have to send all the data back to the
client and request that the form be resubmitted with correct
information.
 JavaScript provides a way to validate form's data on the client's
computer before sending it to the web server.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 30


 Form validation generally performs two functions.
 Basic Validation − the form must be checked to make
sure all the mandatory fields are filled in.
 Data Format Validation − the data that is entered must be
checked for correct form and value.
 We will take an example to understand the process of
validation. Next is a simple form in html format.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 31


<html> <head> <title>Form Validation</title> <tr><td align = "right">Country</td>

<script type = "text/javascript"> </script> </head> <td> <select name = "Country">

<body> <option value = "-1" selected>[choose yours]</option>

<form action = “test.jsp" name = "myForm" onsubmit = <option value = "1">USA</option>


"return(validate());"> <option value = "2">UK</option>
<table cellspacing = "2" cellpadding = "2" border = "1"> <option value = "3">INDIA</option>
<tr> <td align = "right">Name</td> </select> </td> </tr>
<td><input type = "text" name = "Name" /></td> </tr> <tr> <td align = "right"></td>
<tr><td align = "right">EMail</td> <td><input type = "submit" value = "Submit" /></td></tr>
<td><input type = "text" name = "EMail" /></td> </tr> </table>

<tr><td align = "right">Zip Code</td> </form>

<td><input type = "text" name = "Zip" /></td></tr> </body>


</html>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 32


Basic Form Validation
 First let us see how to do a basic form validation. In the above
form, we are calling validate() to validate data when on
submit event is occurring.
 The following example shows the implementation of this
validate() function.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 33


<head> if( document.myForm.Zip.value == "" || isNaN(
document.myForm.Zip.value ) ||
<title>Form Validation</title>
document.myForm.Zip.value.length != 5 ) {
<script type = "text/javascript">
alert( "Please provide a zip in the
function validate() { format #####." );
if( document.myForm.Name.value == "" document.myForm.Zip.focus() ;
){
return false; }
alert( "Please provide your name!" );
if( document.myForm.Country.value == "-1" ) {
document.myForm.Name.focus() ;
alert( "Please provide your country!" );
return false; }
return false; }
if( document.myForm.EMail.value == "" ) {
return( true ); }
alert( "Please provide your Email!" );
</script>
document.myForm.EMail.focus() ;
</head>
return false; }

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 34


Data Format Validation
 Now we will see how we can validate our entered form data
before submitting it to the web server.
 The following example shows how to validate an entered
email address. An email address must contain at least a ‘@’
sign and a dot (.). Also, the ‘@’ must not be the first
character of the email address, and the last dot must at least
be one character after the ‘@’ sign.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 35


<script type = "text/javascript">
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false; }
return( true ); }
</script>
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 36
 Web Browsers and Servers use HTTP protocol to communicate
and HTTP is a stateless protocol.
 But for a commercial website, it is required to maintain session
information among different pages.
 For example, one user registration ends after completing many
pages. But how to maintain users' session information across all
the web pages.
 In many situations, using cookies is the most efficient method of
remembering and tracking preferences, purchases,
commissions, and other information required for better visitor
experience or site statistics.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 37


 A cookie is a piece of data which is sent from a website and
stored locally by the user’s browser.
 Allows to store particular information about a user and
retrieve it every time they visit your pages.
 Each user has their own unique set of cookies.
 Cookies are typically used by web servers to perform
functions such as tracking your visits to websites, enabling
you to log in to sites, and storing your shopping cart, etc.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 38


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

How It Works ?
 Your server sends some data to the visitor's browser in the form of a
cookie.
 The browser may accept the cookie. If it does, it is stored as a plain text
record on the visitor's hard drive.
 Now, when the visitor arrives at another page on your site, the browser
sends the same cookie to the server for retrieval.
 Once retrieved, your server knows/remembers what was stored earlier.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 39


 Cookies are a plain text data record of 5 variable-length fields −
 Expires − The date the cookie will expire.
 Domain − The domain name of your site.
 Path − The path to the directory or web page that set the cookie.
 Secure − If this field contains the word "secure", then the cookie may only
be retrieved with a secure server.
 Name=Value − Cookies are set and retrieved in the form of key-value pairs

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 40


Storing Cookies
 The simplest way to create a cookie is to assign a string value to
the document.cookie object, which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
 Here the expires attribute is optional. If you 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, you may want to use the JavaScript
escape() function to encode the value before storing it in the
cookie.
 Try the following. It sets a customer name in an input cookie.
ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 41
<html> <body>
<head>
<form name = "myform" action =
<script type = "text/javascript">
"">
<!--
function WriteCookie() {
Enter name: <input type = "text"
name = "customer"/>
if( document.myform.customer.value == "" ) {
alert("Enter some value!"); <input type = "button" value =
"Set Cookie" onclick =
return;
"WriteCookie();"/>
}
cookievalue = escape(document.myform.customer.value) + ";";
</form>
document.cookie = "name=" + cookievalue; </body>
document.write ("Setting Cookies : " + "name=" + cookievalue ); </html>
}
//-->
</script>
</head>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 42


Reading Cookies
 The simplest way to create a cookie is to assign a string value to
the document.cookie object, which looks like this.
 Reading a cookie is just as simple as writing one, because the
value of the document.cookie object is the cookie. So you can use
this string whenever you want to access the cookie.
 The document.cookie string will keep a list of name=value pairs
separated by semicolons, where name is the name of a cookie
and value is its string value.
 You can use strings' split() function to break a string into key and
values as follows

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 43


<html> <body>
<head>
<form name = "myform" action =
<script type = "text/javascript">
"">
function ReadCookie() {
var allcookies = document.cookie;
<p> click the following button
and see the result:</p>
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array <input type = "button" value =
"Get Cookie" onclick =
cookiearray = allcookies.split(';');
"ReadCookie()"/>
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
</form>
name = cookiearray[i].split('=')[0]; </body>
value = cookiearray[i].split('=')[1]; </html>
document.write ("Key is : " + name + " and Value is : " +
value); } }
</script>
</head>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 44


Setting Cookies Expiry Date
 You can extend the life of a cookie beyond the current browser
session by setting an expiration date and saving the expiry date
within the cookie.
 This can be done by setting the ‘expires’ attribute to a date and
time.
 Try the following example. It illustrates how to extend the expiry
date of a cookie by 1 Month.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 45


<script type = "text/javascript">
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 46


Deleting a Cookie
 Sometimes you will want to delete a cookie so that subsequent
attempts to read the cookie return nothing. To do this, you just
need to set the expiry date to a time in the past.
 Try the following example. It illustrates how to delete a cookie by
setting its expiry date to one month behind the current date.

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 47


<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue ); }
</script>

ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 48


ASU/Computing/Computer Scienc Internet Programing/2019 by Seiyfu Y. 49

You might also like