Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 57

Internet Programming -1

 JavaScript
 XML Basic

 Internal (40 Marks)


 Internal Exam – 25 Marks
 Assignment – 13 Marks
 Attendance – 02 Marks

Total 40 Marks

 External (60 Marks)


1
Scripting Language :
 A Scripting Language is a programming
Language that is used to manipulate, customise,
and automate the facilities of an existing system.
 In such systems, useful functionality is already
available through a user interface, and the
scripting language is a mechanism for exposing
that functionality to program control.
Scripting languages are easier to learn than
compiled languages.
Scripts get more done in less code and less
coding time than compiled languages.

2
Types of Scripting
Server Side Scripting
Client Side Scripting

Example of Scripting Language


JavaScript
VBScript
 Perl
 Python
 PHP
TCL (Tool Command Language)

3
Server Side Or Client Side
• Server-side • Client-side
– Processed by server – Processed by browser
– Does not rely on – Does not depend on
browser support web server
– Provide browser with requirements
data that does not – Does not need to
reside on client interact with server to
– Script code not visible create content
in page source • processed by
– Can browser
• Manage sessions – Script code is viewable
(shopping baskets, in page source
etc.)
• Database
processing 4
JavaScript Basics
 What JavaScript is:
– interpreted programming language.
Interpreted means that the entire web page is
downloaded to the browser and the JavaScript code is
executed when an event is triggered. When the code is
executed it is interpreted one line at a time. There are a
number of events that will trigger the execution of a
JavaScript, like a click on a form button, or the completion
of a web page loading.
– Extension of HTML
– An object-based scripting language.
You can create new objects in JavaScript (or use the
predefined ones), but not by inheriting from existing
objects like fully-fledged object-oriented languages (C#,
C++ or Java).
5
-Loosely typed
Languages like C# or C++ require that you declare the
data type of the variables you are using. JavaScript does not.
Most functions (for example, alert() ) will happily accept
variables of different types and if needed convert them on the
fly from one type to another.
-Meant for "client-side" scripting
When visitors come to your web pages spiced with
JavaScript, the code executes on their machines. By
comparison, PHP code executes on the web server ("server-
side" scripting) to output the HTML code, which is then fed to
visitor's web browsers.
•What JavaScript isn’t:
– Java
– A full object-oriented program Environment
•What JavaScript enables:
6
– Interactivity
What Can JavaScript Do

• Accept Input
– Text fields, check boxes, buttons, etc.
• Process Data
– Make decisions, manipulate variables
• Produce Output
– Messages, status lines, windows…
• Why?
– HTML doesn’t do much

7
What Can JavaScript Do?

• Modify Pages on the Fly


– Change text, replace images, special effects
• Offer Selections to the User
– Drop down menus, check boxes, buttons
• Manipulate Windows
– Open windows, write to them, close them
• BUT: no reading or writing to user’s disk

8
Putting JavaScript into Pages

 Direct Insertion
– Inside <head> tags (deferred script)
– Within <body> (immediate script)
 Embedded inline
– Inside other HTML tags (as attribute values
 External references
– In external .js files (as deferred functions)

9
JavaScript Language
• Objects
– Things on a page
Example
Img, form, checkbox, button, textarea
• Attributes / Properties
– Properties of objects
Example : Height, width, src, href, bgcolor, name etc.
document.bgcolor (document is the object.,bgcolor is
the property )
• Methods
– Actions taken by objects
Example
10
write,Onclick, focus, alert, getDate(), scroll
JavaScript Language

• Statements
– Lines of assembled components
Example
Document.myimage.src=“somepic.jpg”

• Functions
– Reusable groups of statements
Example
Function doSomething()
{
…… statements …..
}
11
Event Handlers

 Special methods associated with certain objects.


 Called automatically when events occur
 You specify what happens

– onClick, onMouseDown, onMouseUp


– onFocus, onBlur, onKeyPress
– onLoad, onUnload, onSubmit

12
Object Hierarchy
 Fully-qualified location of an Object
 Allows multiple instances of similar objects
 Avoids duplication of object names
Window
Document
Form
Object
Property or method
Value or action
– Document.form1.button3.value=“Click me”

13
Programming JavaScript
 Variables
– Named elements that can change value
Example:
month, numberRight, score, Total

 Data types
– Integer, floating-point, boolean, string
Example:
12, 987.654, true/false, “Texas Tech”

 Operators
– Assignment, comparison, boolean, string
Example:
>=, ==, +=, ||, <, >, etc.

14
Programming JavaScript
 Control statements
– Conditions, loops
Example
If, if….else, for, etc.

 Keywords
– Reserved words with special meaning
Example
Var, true, false, int, const, new, return

15
Programming Rules
 Case matters
 Quotes (or not) matter
 Matching braces matter
 Use indenting and semicolons
<script language=“javascript”>
Function msgBox(boxText)
{
Alert(boxText);
}
</script>

16
Placement in head or body of html

 Typically function definitions or code for handling events


is placed in the head (and accessed if/as needed).
 Script meant to be processed just once as part of
document content goes in the body. Scripts in the head
are cataloged but not interpreted at that time. Scripts in
the body are processed as encountered.
- Scripts in the <BODY> section will be executed
WHILE the page loads, while the Scripts in the <HEAD>
section will be executed when CALLED.

17
Adding Comments :
 Comments are useful for providing additional information
for debugging and remembering what you did
 Single line comments - (// )
// comment text
 Multi-line comments (/* */)
/* comments
More comments */
 Hiding from older browsers
<script type=“text/javascript”>
<!-- This will hide JavaScript from older browsers Script -->
</script> 18
Variables :
The names of the variables and functions must follow these
simple rules.
 The first character must be a letter of the alphabet
(lowercase or uppercase), an underscore (_) or a dollar sign
($). The dollar sign is not recommended as it is not
supported prior to JavaScript ver 1.1.
You CANNOT use a number as the first character of the
name.
Names CANNOT contain spaces.
Names CANNOT match any of the reserved words.
Examples of valid names:
x
add_two_num
x13
_whatever
$money_string
19
Reserved Words in Javascript
There are a number of words that make up the components
of the JavaScript language. These words cannot be used for
variable or function names because the program interpreter
would be unable to distinguish between a default JavaScript
command and your variable or function name.
Example:
abstract ,delete ,innerWidth ,Packages ,status ,
alert ,do ,instanceof ,pageXOffset ,statusbar ,
break,for,super,void,case,function,switch,
while,catch,else,if,this,with,class,enum,import,
throw,const,export,in,true,continue,
extends,new,try,debugger,false,null,
typeof,default ,finally,return,var

20
Execution of JavaScript Programs
 HTML parser – Takes care of processing an html document
 JavaScript interpreter – Takes care of processing JavaScript
code
HTML parser – must stop processing an html file when
JavaScript code is found (JavaScript interpreter will then
be running)
This implies a page with JavaScript code that is
computationally intensive can take a long time to load

21
Writing Output to the Webpage :
 Use the following command to write to a webpage
document.write(“Wow! I wrote my first script”);
• document is the object
• write is the method
 You can include HTML tags
document.write(“<h1>Wow! I don’t see any tags.</h1>”);

22
Simple Script Example :
<html>
<head><title>My First Script</title></head>
<body>
<script language=“javascript”>
document.write(“Welcome to Javascript”);
</script>
</body>
</html>

23
JavaScript Example :
<HTML>
<HEAD> <TITLE>Our First Script</TITLE> </HEAD>
<BODY> <CENTER>
<H1>Our First Script</H1>
</CENTER> <P>Today is
<SCRIPT Language="JavaScript">
<!-- hide from old browsers
var today = new Date()
document.write(today) //-->
</SCRIPT>
24
</BODY> </HTML>
Other Output Types :
 Alert Box: an alert box will display specified text in
a box that contains an ok button.
 Are generally used for warnings.
alert(“Alert text is printed in an alert box”);
 Confirm box: an alert box that contains text –
usually in the form of a question – and an OK and
Cancel button.
confirm(“Type your question between the quotes
– ok?”);
25
 Prompt Box: an alert box that prompts the user
to input text.
Provide 2 pieces of information:
– Text to be displayed – usually a question
– Initial value of the text box
prompt(“What is your name”, ”Enter your name
here”);
prompt(“What is your favorite school?”,
“SICSR”)

26
Declaring Variables :
A variable is a name assigned to a location in a computer's
memory to store data. Before you can use a variable in a
JavaScript program, you must declare its name.
Variables are declared with the var keyword, like this:
var x;
var y;
You can also declare multiple variables with the same var
keyword.
var x, y, sum;
 you can combine variable declaration with initialization.
var x = 1, y = 3, sum = 0;
If you don't specify an initial value for a variable when you
declare it, the initial value is a special JavaScript undefined
value.
Remember: JavaScript is case-sensitive so x and X are two
different variable names. 27
Scope of the variable:
The variables you declare can be global or local.
If you declare a variable outside of any function definition,
it is a global variable.
 It lives for as long as your application lives. Any part of
your program can access the global variable and change its
value.
 Variables created inside functions with the keyword var
are local.
Local variables have short lives: they come into existence
when the function is invoked, and disappear when the
function exits.
The local variable can only be used and its value modified
inside of a function declaring it.
A global and a local variable with the same name can
coexist. They are in every way two different variables and
modifying one does not affect the other. 28
Example :
str = "This is a global string";
function MyFun()
{
var str = "This is a local string";
document.write(str); }
MyFun();
Document.write(“<br>”);
document.write(str);

OUTPUT:
This is a local string.
This is a global string.

29
Insert Special Characters
 insert special characters (like " ' ; &) with
the backslash
Example:
document.write ("You \& I sing \"Happy
Birthday\".")
OUTPUT:
You & I sing "Happy Birthday".

30
Concatenation Operator (+) :
 Concatenation is a process of combining two strings into
one longer string.
‘+’ will act as concatenation operator in Javascript.
Example:
1) <script language="javascript">
var string1, string2, stringConcatenated;
string1 = “Java"; // first string
string2 = “script"; // second string
stringConcatenated = string1 + string2; // Concatenating
strings
document.write (stringConcatenated); // printing the
Concatenated string
</script>
OUTPUT: Javascript
31
2) script language="javascript">
var strOut;
strOut = "<table width='300' border='1' cellspacing='0'
cellpadding='3'>";
strOut = strOut + "<tr>";
strOut = strOut + "<th colspan='2'>The + operator in
JavaScript</th>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<th>When used in</th>";
strOut = strOut + "<th>Performs</th>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<td>Mathematical
expression</td>";
strOut = strOut + "<td>Addition</td>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<td>String expression</td>";
strOut = strOut + "<td>Concatenation</td>";
strOut = strOut + "</tr>";
strOut = strOut + "</table>";
document.write (strOut);
32
</script>
Data Types In JavaScript :
 Numeric
 String
 Boolean
 Array
 Object

 Type is assigned at run time:


Example :
 var item; // item is undefined (Default)
 item = 10; // item is now an integer
 item = 'ten'; // item is now a string

33
Operators :
Operators are used to handle variables.

Types of operators with examples:


 Arithmetic operators, such as plus.
 Comparisons operators, such as equals.
 Logical operators, such as and.
 Control operators, such as if.
 Assignment and String operators

34
JavaScript Operators :
 Arithmetic Operators
Eg. : + - * / %
 Comparison Operators
Eg. : == != < > <= >=
 Logical Operators
Eg. : && || !
 Bitwise Operators
Eg. : & | ^ >> >>> <<
 Ternary Operators
Eg. : ?:

35
Arithmetic Operators :
Operator Description Example Result

+ Addition x=2 4

y=2

x+y

- Subtraction x=5 3

y=2

x-y

* Multiplication x=5 20

y=4

x*y

/ Division 15/5 3

5/2 2,5

% Modulus (division remainder) 5%2 1

10%8 2

10%2 0

++ Increment x=5 x=6

x++

-- Decrement x=5 x=4

x--

36
Assignment Operators :
Operator Example Is The Same As

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y

37
Comparison Operators :
Operator Description Example

== is equal to 5==8 returns false

=== is equal to (checks for both value and type) x=5

y="5"

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true

38
Logical Operators :
Operator Description Example

&& and x=6

y=3

(x < 10 && y > 1) returns true

|| or x=6

y=3

(x==5 || y==5) returns false

! not x=6

y=3

!(x==y) returns true

39
Bitwise Operators : & | ^ >> >>> <<
The bitwise operators convert the operand to a 32-bit signed
integer, and turn the result back into 64-bit floating point.

Ternary Operator : ?:
Example :
greeting=(visitor=="PRES")?"Dear President ":"Dear "

If the variable visitor is equal to PRES, then put the string "Dear
President " in the variable named greeting. If the variable visitor
is not equal to PRES, then put the string "Dear " into the
variable named greeting.

40
Operator Precedence :
The precedence of the operator determines which operations
are evaluated before others during the parsing and execution
of complex expressions.
Precedence Operator
1 Parentheses, array subscripts, or function call
2 !, ~, -, ++, --
3 *, /, %
4 +, -
5 <<, >>, >>>
6 <, <=, >, >=
7 ==, !=
8 &
9 ^
10 |
11 &&
12 ||
13 ?:
14 =, +=, -=,*=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=
41
Example Of Arithmetic Operators :
<html><head>
<script language= "JavaScript">
s1=12 ;
s2=28;
add1=s1+s2;
sub1=s1-s2;
mul1=s1*s2;
div1=s1/s2;
document.write("<br>Example of arithmetic operator
...<br>");
document.write("<br>Addition is : "+add1);
document.write("<br>Subtraction is: "+sub1);
document.write("<br>Multiplication is: "+mul1);
document.write("<br>Division is: "+div1);
</script >
</head></html> 42
Statements :
expression
if
switch
while
do
for
break
continue
return
try/throw

43
Conditional Statements :
►Very often when you write code, you want to perform
different actions for different decisions. You can use
conditional statements in your code to do this.

In JavaScript we have the following conditional statements:


►if statement - use this statement if you want to execute
some code only if a specified condition is true
►if...else statement - use this statement if you want to
execute some code if the condition is true and another code
if the condition is false
►if...else if....else statement - use this statement if you
want to select one of many blocks of code to be executed
►switch statement - use this statement if you want to
select one of many blocks of code to be executed .
44
Syntax :
if (condition)
{
code to be executed if condition is true
}
if (condition)
{ code to be executed if condition is true }
else
{ code to be executed if condition is not true }
Example :
<script language=“Javascript”>
x=3
if(x<0)
{ alert (“negative”)
}
else
{ alert (“positive”)
}
45
</script>
Switch Statement :
•Multiway branch
•The switch value does not need to a number. It can be a
string.
•The case values can be expressions.
Syntax :
switch (expression) {
case ';':
case ',':
case '.':
punctuation();
break;
default:
noneOfTheAbove( );
} 46
Break & Continue Statement :
- Alter flow of control
break;
❍Exits structure
continue;
❍Skips remaining statements in structure; continues with next loop
iteration
When used properly
❍Performs faster than the corresponding structured techniques

47
Example of Break :
<HTML>
<HEAD>
<TITLE> Using the break Statement in a for Structure </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
for ( var count = 1; count <= 10; ++count ) {
if ( count == 5 )
break; // break loop only if count == 5
document.writeln( "Count is: " + count +
"<BR>" );
}
document.writeln( "Broke out of loop at count = " + count
);
</SCRIPT>
</HEAD>

<BODY></BODY>
</HTML>
48
Example Of Continue :
<HTML>
<HEAD>
<TITLE> Using the continue Statement in a for Structure </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
for ( var count = 1; count <= 10; ++count ) {
if ( count == 5 )
continue; // skip remaining code in loop only if
count == 5
document.writeln( "Count is: " + count + "<BR>" );
}
document.writeln( "Used continue to skip printing 5");
</SCRIPT>
</HEAD>

<BODY></BODY>
</HTML>

49
Throw Statement :

throw new Error(reason);

throw {
name: exceptionName,
message: reason
};

50
Try Statement :
•The JavaScript implementation can produce these
exception names:
1) 'Error‘ 2) 'EvalError‘ 3) 'RangeError‘
4) 'SyntaxError‘ 5) 'TypeError‘ 6) 'URIError'
Example :
try { ...
} catch (e) {
switch (e.name) {
case 'Error':
...
break;
default:
throw e;
}
}
51
Return Statement :
return expression;

•or
return;

•If there is no expression, then the


return value is undefined.
•Except for constructors, whose default
return value is this.

52
Looping :
Very often when you write code, you want the same
block of code to run a number of times. You can use
looping statements in your code to do this.
In JavaScript we have the following looping statements:
 while - loops through a block of code while a condition
is true
 do...while - loops through a block of code once, and
then repeats the loop while a condition is true
 for - run statements a specified number of times

53
Syntax :
While
Syntax: while (condition)

{
code to be executed
}
do...while
Syntax: do {

code to be executed
} while (condition)
For
Syntax: for (initialization; condition; increment)

{
code to be executed
} 54
Example of for loop :

<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
}
</script></body></html>
55
Example of do – while loop :

<html>
<body>
<script type="text/javascript">
i=1
do
{ document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
i++
}
while (i <= 6)
</script></body></html> 56
57

You might also like