104
JavaScript and Ajax Mohan Bang

JavaScript and Ajax

Embed Size (px)

DESCRIPTION

JavaScript Ajax

Citation preview

Page 1: JavaScript and Ajax

JavaScript and Ajax

Mohan Bang

Page 2: JavaScript and Ajax

Agenda:

Conclusion and Summary3

Ajax32

JavaScript1

Page 3: JavaScript and Ajax

In this presentation, will discuss about …

Types of Scripting Language

What is client-side vs. server-side validation?

Why a re-introduction?

How JavaScript begins?

What is JavaScript?

Browser Versions and JavaScript Support

Why did we require JavaScript?

JavaScript compared to Java

Page 4: JavaScript and Ajax

Overview on JavaScript

Variable Naming

Types of values

Escape characters

Type casting

Conversion Functions

Operators

Built-in objects

Monitoring User Events

DOM Parser

Memory Leaks

JavaScript in Projects

Conclusion and Summary

Page 5: JavaScript and Ajax

Types of Scripting Language

JScript

ActionScript

ECMAScript

JavaScript

VBScript

Page 6: JavaScript and Ajax

What is client-side vs. server-side validation?

client-side validation (client-tier)

Java Script is used for client-side validation. Validation takes place in client-side within your browser. Java Script can be used to submit your form data after successful validation. No extra network trip is required when there are validation errors because form does not have to be submitted

server-side validation (presentation-tier)

Form data is submitted to the server and validation is carried out in the server. Extra network round trip is required when there are validation errors because validation errors need to be reported back to the client and the form data has to be resubmitted.

Page 7: JavaScript and Ajax

Why a re-introduction?

Because JavaScript has a reasonable claim to being the world's most misunderstood programming language. While often derided as a toy, beneath its deceptive simplicity lie some powerful language features. The past year has seen the launch of a number of high profile JavaScript applications, showing that deeper knowledge of this technology is an important skill for any web developer.

Page 8: JavaScript and Ajax

How JavaScript begins?

It is useful to start with an idea of the language's history. JavaScript was created in 1995 by Brendan Eich, an engineer at Netscape, and first released with Netscape 2.0 early in 1996. It's was originally going to be called LiveScript, but was renamed in an ill-fated marketing decision to capitalise on the popularity of Sun Microsystem's Java language - despite the two having very little in common. This has been a source of confusion ever since.

Microsoft released a mostly-compatible version of the language called JScript with IE 3.0 several months later.

Netscape submitted the language to ECMA ((European Computer Manufacturers Association) International, a European standards organisation, which resulted in the first edition of the Ecmascript standard in 1997. The standard received a significant update as Ecmascript edition 3.0 in 1999, and has stayed pretty much stable ever since - although edition 4.0 is currently in the works.

Page 9: JavaScript and Ajax

What is JavaScript?

JavaScript is Netscape’s cross-platform, object-based scripting language for client and server applications.

Client-side JavaScript extends the core language by supplying objects to control a browser (Navigator or another web browser) and its Document Object Model (DOM).

Using JavaScript, you can create dynamic HTML pages that process user input.

Page 10: JavaScript and Ajax

Browser Versions and JavaScript Support

Each version of Browser(Internet Explorer / Mozilla Firefox / Netscape Navigator) supports a different version of JavaScript. To help you write scripts that are compatible with multiple versions of Browser, the below table lists the JavaScript version in which each feature was implemented. Versions of Browser prior to 2.0 do not support JavaScript.

Page 11: JavaScript and Ajax

Browser Versions and JavaScript Support

For example the below JavaScript Function is only present in JavaScript 1.3 and above

decodeURI() : Decodes an encoded URI and encodeURI() : Encodes a string as a URI

Definition and Usage : The decodeURI() function decodes a URI encoded with the encodeURI() function.

Syntax : encodeURI(URIstring) ; decodeURI(URIstring) ;

Parameter Description : URIstring Required. The URI to be decoded

In below example we use decodeURI() to decode a URI after encoding it using encodeURI()

<script type="text/javascript">var test="http://www.test.com/Home page/"document.write(encodeURI(test)+ "<br />")</script>

The output of the code above will be:http://www.test.com/Home%page/

Page 12: JavaScript and Ajax

Why did we require JavaScript?

To generating HTML dynamically

To customize Web Pages

To make pages more dynamic

To validate input form

To manipulate HTTP Cookies

To interact with and control frames

Page 13: JavaScript and Ajax

JavaScript compared to Java

J avaScript J ava

Interpreted (not compiled) by client.

Compiled bytecodes downloaded from

server, executed on client.

Object-oriented. No distinction

between types of objects.

Inheritance is through the prototype

mechanism, and properties and

methods can be added to any object

dynamically.

Class-based. Objects are divided into

classes and instances with all

inheritance through the class hierarchy.

Classes and instances cannot have

properties or methods added dynamically.

Code integrated with, and embedded

in, HTML.

Applets distinct from HTML (accessed from

HTML pages).

Variable data types not declared. Variable data types must be declared.

Page 14: JavaScript and Ajax

Overview on JavaScriptVariable Naming

Variable names can begin with :

Uppercase letter (A through Z), Lowercase letter (a through z), Underscore character (_), Dollar sign character ($). The remaining characters can consist of letters or digits

(0 through 9). For example: Sum1 , total ,qty2_1 , _count, Next_Count

Variable names are case sensitive.

JavaScript does not require you to specify the type of the data contained in a variable.

Page 15: JavaScript and Ajax

Types of values

JavaScript supports the following types of values:

Number – This consists of numbers including both integer and floating-point.

String – This consists of text specified within single or double quotes.

Null – This consists of “null” value.

Boolean – This consists of Boolean values “true” and “false”.

Page 16: JavaScript and Ajax

String Value

Alphanumeric data in JavaScript is known as “String”.

String is one or more characters enclosed within single or double quotes.If a string begins with single quote then it has to end with a single quote.

For Example: s1 = ‘This is a sample string’

The quote characters (“ “ or ‘ ‘) can be embedded in a string, but backslash (\) escape characters must precede the quote characters to suppress their meaning.

For Example: “This is a string which displays \“\” on the screen”

Page 17: JavaScript and Ajax

null Value

This can be used with all JavaScript types.

The “null” value indicates that a variable is un-initialized.

Page 18: JavaScript and Ajax

Boolean Value

JavaScript supports a pure Boolean type.

It consists of two values true and false.

JavaScript automatically converts true or false in to 1 or 0.

Page 19: JavaScript and Ajax

Escape characters

Escape characters that can be used in JavaScript

Character Meaning

\’ Single Quote

\” Double Quote

\\ Backslash

\r Carriage Return

\f Form Feed

\n New Line

\b Backspace

\t Tab

Page 20: JavaScript and Ajax

Type casting

JavaScript automatically converts values from one type to another when they are used in expressions.

Adding together the floating-point literal 7.5 and the string "12" results in the floating point numeric literal 19.5.

This type of automatic conversion from one type to another is known as type casting.

In later versions of JavaScript, however, this kind of type casting is not supported.

Page 21: JavaScript and Ajax

Conversion Functions

Explicit conversions can be done using the following functions:

eval() – This function converts a string to a numerical value

parseInt() – This functions extracts the first integer part from a given string

parseFloat() – This function extracts the first floating-point number from the given string

Page 22: JavaScript and Ajax

Operators

Assignment Operators

Comparison Operators

Arithmetic Operators

Logical Operators

String Operators

Bitwise Operators

Special Operators (typeof operator)

Page 23: JavaScript and Ajax

Assignment Operators

Compound Assignment operators

What they imply

A += B A = A + B

A -= B A = A – B

A *= B A = A* B

A /= B A = A / B

Page 24: JavaScript and Ajax

Comparison Operators

Operator Description

Equal (= =) If operands are equal, the expression results in a value true.

Not equal to (!=) If the operands are not equal, the expression results in a value true

Greater than (>) If left operand is greater than right, expression results in a value true

Less than (<) If left operand is less than right, expression results in a value true

Greater than or equal to (>=)

If left operand is greater than or equal to right, expression results in a value true

Less than or equal to (<=)

If left operand is less than or equal to right, expression results in a value true

Relational operators used for comparison and they return a logical value true or false based on the comparison.

The operands can be either numerical or string values.

Page 25: JavaScript and Ajax

Arithmetic Operators

These are the common binary mathematical operators such as Plus (+), Minus (-), Multiplication (*) and Division (/).

In addition to these standard arithmetic operators, there are a few more such as the Increment (++), Decrement (--), Negation (-), and Modulus (%) operators.

Page 26: JavaScript and Ajax

Logical Operators

Logical operators take Boolean values (true or false) as operands and returns a Boolean value.

Operator Description

And ( && )

expr1 && expr2

Returns true if both expr1 and expr2 are true else it returns false

Or ( || )

expr1 || expr2

Returns true if either expr1 or expr2 is true or both else it returns false

Not ( ! )

!expr

Returns false if the expression is true, and true if it is false

Page 27: JavaScript and Ajax

String Operators

The string operator is used for string manipulation. JavaScript only supports string concatenation operator (+).

Page 28: JavaScript and Ajax

Bitwise Operators

Bitwise operators treat the operands as bits rather than numerical value.

The numerical values could be of any base: decimal, octal or hex.

The Bitwise operator will convert the operand to its binary representation and accordingly return a 1 or a 0

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows: 15 & 9 yields 9 (1111 & 1001 = 1001) 15 | 9 yields 15 (1111 | 1001 = 1111) 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)

Page 29: JavaScript and Ajax

Bitwise Operators

Operator

Description Example

<< (Left shift)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.

>> (Sign-propagating right shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.

9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2.

>>> (Zero-fill right shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.

19>>>2 yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Page 30: JavaScript and Ajax

Special Operators (typeof operator)

typeof (operand)

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned.

Page 31: JavaScript and Ajax

Special Operators (typeof operator)

Suppose you define the following variables: var myFun = new Function("5+2")var shape="round"var size=1var today=new Date()

The typeof operator returns the following results for these variables: typeof myFun is objecttypeof shape is stringtypeof size is numbertypeof today is objecttypeof dontExist is undefined

Page 32: JavaScript and Ajax

Built-in objects

JavaScript predefined objects

The Array object

The String object

The Date object

The Boolean object

The Function object

The Math object

The Global object

Page 33: JavaScript and Ajax

Array object

Arrays are declared using Array() constructor.

Example:var firstArray = new Array();var secondArray = new Array(“red” , “green” , “blue”);var thirdArray = new Array(5);

Page 34: JavaScript and Ajax

Array object methods

toString(): Converts an array to a string. The array elements are separated by commas.

join(separator): Joins array elements together but separated by the separator string. The function returns the output as string.

sort(): Sorts the contents of an array based upon the ascii value of each character.

reverse(): Reverses the contents of an array. The last element becomes first and the first element becomes the last.

Page 35: JavaScript and Ajax

Array Object Example

<HTML><HEAD><TITLE> The Array Object </TITLE></HEAD><BODY><BR><BR><H1 ALIGN="CENTER"> The Array Object </H1><HR><SCRIPT LANGUAGE = "JavaScript">myArray=new Array(1,4,3,2,7,6,5,9,8,6,0)document.write("<PRE>")document.write("myArray.toString()\t:\t\t")document.write(myArray.toString()+"<BR>")document.write("myArray.join('-')\t:\t\t")document.write(myArray.join("-")+"<BR>")document.write("myArray.reverse()\t:\t\t")document.write(myArray.reverse()+"<BR>")document.write("myArray.sort()\t\t:\t\t")document.write(myArray.sort()+"<BR>")document.write("</PRE>")</SCRIPT></BODY></HTML>

Page 36: JavaScript and Ajax

The String Object

Strings are declared using String() constructor

var s = new String();var s1=new String(“hello”);

Page 37: JavaScript and Ajax

Methods of String object

toLowerCase(): Converts the entire string to lowercase.

toUpperCase(): Converts the entire string to uppercase.

substring(index): Returns a sub-string from a string beginning at index.

substring(index1, index2): Returns a sub-string from a string beginning at index1 andending at index2.

split(separator): Separates the entire string into an array of sub strings based upon the separator (de-limiter) character.

charAt(index): Returns the character at the specified index.

charCodeAt(index): Returns the character code (UNICODE) of the character at the specified index.

indexOf(pattern): Returns the index of first occurrence of the substring considering the initial index at zero(0).

Page 38: JavaScript and Ajax

String object Example

<HTML><HEAD><TITLE> The String Object </TITLE></HEAD><BODY><BR><BR><H1 ALIGN="CENTER"> The String Object </H1><HR><SCRIPT LANGUAGE = "JavaScript">myString=new String("This is first string. This is second string")document.write("<PRE>")document.write("myString.toLowerCase()\t\t:")document.write(myString.toLowerCase()+"<BR>")document.write("myString.toUpperCase()\t\t:")document.write(myString.toUpperCase()+"<BR>")document.write("myString.substring(7)\t\t:")document.write(myString.substring(7)+"<BR>")document.write("myString.substring(5,6)\t:")document.write(myString.substring(5,6)+"<BR>")document.write("myString.split('first')\t\t:")document.write(myString.split('first')+"<BR>")document.write("myString.charAt(8)\t\t:")document.write(myString.charAt(8)+"<BR>")document.write("myString.charCodeAt(1)\t\t:")document.write(myString.charCodeAt(1)+"<BR>")document.write("myString.indexOf('first')\t:")document.write(myString.indexOf('first')+"<BR>")document.write("</PRE>")</SCRIPT></BODY></HTML>

Page 39: JavaScript and Ajax

Date Object

Dates are declared using date() constructor

Example:

var rightNow = new Date();var birthDay = new Date(“March 24, 1970”);var someDate = new Date(1970, 2, 24);

Page 40: JavaScript and Ajax

Methods of Date object

getDate() : Returns the day of the month from the Date object.

getDay() : Returns the day of the week from the Date object, starting Monday as 1.

getMonth() : Returns the month of the year from the Date object. It returns ‘0’ for January, ‘1’ for February, so on and ‘11’ for December.

setMonth() : Sets the month of the year for the Date object.

getYear() : Returns the year from the Date object.

setYear() : Sets the year for the Date object.

getFullYear() : Returns the year in four digit format from the Date object.

setFullYear() : Sets the year in four digit format for the Date object.

getTime() : Returns the time in milliseconds since midnight January 1, 1970 from the Date object.

Page 41: JavaScript and Ajax

Boolean Object

The Boolean object allows the creation of user defined boolean values.

Page 42: JavaScript and Ajax

Example: Boolean Object

<HTML><HEAD><TITLE> The Boolean Object </TITLE></HEAD><BODY><H3 ALIGN = “CENTER”> Using The Boolean Object </H3> <HR><PRE><SCRIPT LANGUAGE = “JavaScript”>myTrue = new Boolean(true)myFalse = new Boolean(false)document.write(“true + true :\t”)document.write(true + true)document.write(“<BR>”)document.write(“myTrue + myTrue :\t”)document.write(myTrue + myTrue)document.write(“<BR>”)document.write(“true + false :\t”)document.write(true + false)document.write(“<BR>”)document.write(“myTrue + myFalse :\t”)document.write(myTrue + myFalse)document.write(“<BR>”)document.write(“false + false :\t”)document.write(false + false)document.write(“<BR>”)document.write(“myFalse + myFalse :\t”)document.write(myFalse + myFalse)</SCRIPT></PRE></BODY></HTML>

Page 43: JavaScript and Ajax

Math Object

The Math object is used for performing simple and advanced arithmetic operations.

Properties of Math object :LOG6E This represents the base 6 logarithm of e PI The constant PI value E Euler’s constantLOG2EThe base 2 logarithm of e  LN2 The natural logarithm of 2

Page 44: JavaScript and Ajax

Methods of Math object

abs(x) : This method returns the absolute value of x

cos(x) : This method returns the cosine of x

exp(x) : This method returns the exponential of x

log(x) : This method returns the natural logarithm of x

max(x,y) : This methods returns the maximum of x and y

min(x,y) : This method returns the minimum of x and y

random() : This method returns random number between 0 and 1

round(x) : This method returns x rounded to the closest integer

sin(x) : This method returns the sine of x

sqrt(x) : This method returns the square root of x

tan(x) : This method returns the tangent of x

pow(x,y) : This method returns x to power y

Page 45: JavaScript and Ajax

Global Object

The Global object provides methods, which can be accessed globally.

Page 46: JavaScript and Ajax

Methods of Global object

eval(expression): This method evaluates and returns the value of the expression.

parseInt(string): This method parses the string in to an integer.

parseFloat(string): This methods parses the string as a floating-point number.

isFinite(number): This methods returns true if the number is finite, otherwise false.

isNaN(number): This method returns true if the number is NaN (Not A Number), otherwise false.

Page 47: JavaScript and Ajax

Window Object Timeout and Time Interval

setInterval() methods preforms specified job repeatedly after specified time-interval.

setInterval(‘alert(“4 seconds over”)’,4000) displays alert dialog box after every 4 seconds, for an infinite number of times. This returns interval reference to a variable.ref = setInterval(“myfunc()”, 4000)

To terminate clearInterval() method can be used as, clearInterval(ref). setTimeout() methods performs specified job

once only after specified time-interval.

ref = setTimeout(“myfunc()”, 4000) calls myfunc()after 4 seconds for once only.

Page 48: JavaScript and Ajax

Monitoring User Events

JavaScript Event :Events are normally used in combination with functions, and the function will not be executed before the event occurs!

The ability to let HTML events trigger actions in the browser, like starting a JavaScript when a user clicks on an HTML element. Below is a list of the attributes that can be inserted into HTML tags to define event actions.

Page 49: JavaScript and Ajax

JavaScript Event

Attribute The event occurs when...onabort Loading of an image is interruptedonblur An element loses focusonchange The content of a field changesonclick Mouse clicks an objectondblclick Mouse double-clicks an objectonerror An error occurs when loading a document or an imageonfocus An element gets focusonkeydown A keyboard key is pressedonkeypress A keyboard key is pressed or held downonkeyup A keyboard key is releasedonload A page or an image is finished loadingonmousedown A mouse button is pressedonmousemove The mouse is movedonmouseout The mouse is moved off an elementonmouseover The mouse is moved over an elementonmouseup A mouse button is releasedonreset The reset button is clickedonresize A window or frame is resizedonselect Text is selectedonsubmit The submit button is clickedonunload The user exits the page

Page 50: JavaScript and Ajax

JavaScript and Object Oriented Programming

JavaScript is an excellent scripting language to write object oriented web applications.

Example:

<script language="javascript" type="text/javascript"><!--

person = new Object()person.name = "Tim Scarfe"person.height = "6Ft"

timObject = {property1 : "Hello",property2 : "MmmMMm",property3 : ["mmm", 2, 3, 6, "kkk"],method1 : function(){alert("Method had been called" + this.property1)}

};

timObject.method1();alert(timObject.property3[2]) // will yield 3

//--></script>

Page 51: JavaScript and Ajax

DOM Parser

Types of Parser: DOM and SAX

Parsers -> DOM (Document Object Model) parser

The parsers are fundamentals xml components, a bridge between XML documents and application that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD (Document type definition) or Schema.

Page 52: JavaScript and Ajax

Pros and Cons of DOM Parser

1) Tree of Nodes

2) Memory: Occupies more memory.

3) Preferred for small XML documents

4) Slower at runtime

5) Stored as objects

6) Programmatically easy, since objects are to referred

7) Ease of Navigation

Page 53: JavaScript and Ajax

Document Object Model (DOM)

Introduction

DOM Implementation

DOM with JavaScript

Setup

DOM Components

Creating Nodes

Traversing the DOM

OutlineWe will discuss about …

Page 54: JavaScript and Ajax

Introduction to DOM

A document object model (DOM) - is an application programming interface (API) for representing a document.

Can access and manipulate the various elements that make up that document.

Represents XML documents in a tree structure and defines properties and methods for traversing the tree and examining and modifying its nodes.

Page 55: JavaScript and Ajax

XML Document Object Model (DOM)

W3C standard recommendation

Build tree structure in memory for XML documentsDOM-based parsers parse these structuresExist in several languages (Java, C, C++, Python, Perl, etc.)

Page 56: JavaScript and Ajax

Representing Document as a tree

DOM tree

Each node represents an element, attribute, etc.

<?xml version = "1.0"?><message >

<from>Paul</from> <to>Tim</to> <body>Hi, Tim!</body>

</message>

from body

“Hi, Tim!”

Document

to

TimPaul

Page 57: JavaScript and Ajax

Node created for element message

Element message has child nodes for body,to and from element

Element body has child node for text "Hi, Tim!“ ..

Page 58: JavaScript and Ajax

Interfaces

The Node interface - defines properties and methods for traversing and manipulating the tree

Properties: childNode,firstChild,lastChild

Methods : appendChild( ), removeChild( ), replaceChild( ), and insertBefore( )

Page 59: JavaScript and Ajax

Types of nodes

InterfaceElementTextDocumentCommentDocumentFragmentAttr

nodeType constantNode.ELEMENT_NODENode.TEXT_NODENode.DOCUMENT_NODENode.COMMENT_NODENode.DOCUMENT_FRAGMENT_NODENode.ATTRIBUTE_NODE

Page 60: JavaScript and Ajax

The Node at the root of the DOM tree is a Document object.

The documentElement property of this object refers to an Element object that represents the root element of the document.

Page 61: JavaScript and Ajax

Core DOM

Node

Document

CharacterData

Element

Attribute

Text

Comment

Page 62: JavaScript and Ajax

DOM Implementations

DOM-based parsers

Microsoft’s msxml

Sun Microsystem’s JAXP

Page 63: JavaScript and Ajax

Some DOM-based parsers.

Parser Description

JAXP Sun Microsystem’s Java API for XML Parsing (JAXP) is available at no charge from java.sun.com/xml.

XML4J IBM’s XML Parser for Java (XML4J) is available at no charge from www.alphaworks.ibm.com/tech/xml4j.

Xerces Apache’s Xerces Java Parser is available at no charge from xml.apache.org/xerces.

msxml Microsoft’s XML parser (msxml) version 2.0 is built-into Internet Explorer 5.5. Version 3.0 is also available at no charge from msdn.microsoft.com/xml.

4DOM 4DOM is a parser for the Python programming language and is available at no charge from fourthought.com/4Suite/4DOM.

XML::DOM

XML::DOM is a Perl module that we use in Chapter 17 to manipulate XML documents using Perl. For additional information, visit www-4.ibm.com/software/developer/library/xml-perl2.

Page 64: JavaScript and Ajax

DOM and JavaScript

We use JavaScript and msxml parser

XML document marks up article Use DOM API to display document’s element names/values

Page 65: JavaScript and Ajax

Article marked up with XML tags.

1 <?xml version = "1.0"?>23 <!-- Fig. 8.2: article.xml -->4 <!-- Article formatted with XML -->56 <article>78 <title>Simple XML</title>910 <date>December 6, 2000</date>1112 <author>13 <fname>Tem</fname>14 <lname>Nieto</lname>15 </author>1617 <summary>XML is pretty easy.</summary>1819 <content>Once you have mastered HTML, XML is easily20 learned. You must remember that XML is not for21 displaying information but for managing information.22 </content>2324 </article>

Page 66: JavaScript and Ajax

Traversing article.xml with

JavaScript.

1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"

2 "http://www.w3.org/TR/html4/strict.dtd">

3

4 <html>

5

6 <!-- Fig. 8.3 : DOMExample.html -->

7 <!-- DOM with JavaScript -->

8

9 <head>

10 <title>A DOM Example</title>

11 </head>

12

13 <body>

14

15 <script type = "text/javascript" language = "JavaScript">

16

17 var xmlDocument = new ActiveXObject( "Microsoft.XMLDOM" );

18

19 xmlDocument.load( "article.xml" );

20

Element script allows for including scripting

codeInstantiate

Microsoft XML DOM object

Load article.xml into memory; msxml parses

article.xml and stores it as tree structure

Page 67: JavaScript and Ajax

Traversing article.xml with

JavaScript. (Contd..)

21 // get the root element

22 var element = xmlDocument.documentElement;

23

24 document.writeln(

25 "<p>Here is the root node of the document:" );

26 document.writeln( "<strong>" + element.nodeName

27 + "</strong>" );

28

29 document.writeln(

30 "<br>The following are its child elements:" );

31 document.writeln( "</p><ul>" );

32

33 // traverse all child nodes of root element

34 for ( i = 0; i < element.childNodes.length; i++ ) {

35 var curNode = element.childNodes.item( i );

36

37 // print node name of each child element

38 document.writeln( "<li><strong>" + curNode.nodeName

39 + "</strong></li>" );

40 }

41

42 document.writeln( "</ul>" );

43

44 // get the first child node of root element

45 var currentNode = element.firstChild;

46

Assign article as root element

Place root element’s name in element strong and write it

to browser

Assign index to each child node of

root node

Retrieve root node’s first child

node (title)

Page 68: JavaScript and Ajax

Traversing article.xml with

JavaScript. (Contd..)

47 document.writeln( "<p>The first child of root node is:" );

48 document.writeln( "<strong>" + currentNode.nodeName

49 + "</strong>" );

50 document.writeln( "<br>whose next sibling is:" );

51

52 // get the next sibling of first child

53 var nextSib = currentNode.nextSibling;

54

55 document.writeln( "<strong>" + nextSib.nodeName

56 + "</strong>." );

57 document.writeln( "<br>Value of <strong>" + nextSib.nodeName

58 + "</strong> element is:" );

59

60 var value = nextSib.firstChild;

61

62 // print the text value of the sibling

63 document.writeln( "<em>" + value.nodeValue + "</em>" );

64 document.writeln( "<br>Parent node of " );

65 document.writeln( "<string>" + nextSib.nodeName

66 + "</strong> is:" );

67 document.writeln( "<strong>" + nextSib.parentNode.nodeName

68 + "</strong>.</p>" );

69

70 </script>

71

72 </body>

73 </html>

Siblings are nodes at same level in document (e.g., title, date, author, summary and

content)Get first child’s next sibling

(date)

Get first child of date (December 6, 2000)

Get parent of date (article)

Page 69: JavaScript and Ajax

Traversing article.xml with JavaScript.

Page 70: JavaScript and Ajax

Memory Leaks

An unfortunate side effect of closures is that they make it trivially easy to leak memory in Internet Explorer. JavaScript is a garbage collected language - objects are allocated memory upon their creation and that memory is reclaimed by the browser when no references to an object remain. Objects provided by the host environment are handled by that environment.

Browser hosts need to manage a large number of objects representing the HTML page being presented - the objects of the DOM. It is up to the browser to manage the allocation and recovery of these. Internet Explorer uses its own garbage collection scheme for this, separate from the mechanism used by JavaScript. It is the interaction between the two that can cause memory leaks.

Page 71: JavaScript and Ajax

Memory LeaksA memory leak in IE occurs any time a circular reference is formed between a JavaScript object and a native object. Consider the following:

function leakMemory() {var el = document.getElementById('el');var o = { 'el': el };el.o = o;}

The circular reference formed above creates a memory leak; IE will not free the memory used by el and o until the browser is completely restarted.The above case is likely to go unnoticed; memory leaks only become a real concern in long running applications or applications that leak large amounts of memory due to large data structures or leak patterns within loops.Leaks are rarely this obvious - often the leaked data structure can have many layers of references, obscuring the circular reference.

Page 72: JavaScript and Ajax

JavaScript in Projects

How to implement "Please, Wait..." page?

The client-side solution might be very simple. You can wrap the jsp page (or part of it you want to hide) into the DIV, then you can add one more DIV that appears when user clicks the submit button. This DIV can contain the animated gif you speak about or any other content.

Scenario: when user clicks the button, the JavaScript function is called. This function hides the page and shows the "Wait" DIV. You can customize the look-n-fill with CSS if you like.

Page 73: JavaScript and Ajax

Example: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:loadBundle basename="demo.bundle.Messages" var="Message"/> <html><head> <title>Input Name Page</title> <script> function gowait() { document.getElementById("main").style.visibility="hidden"; document.getElementById("wait").style.visibility="visible"; } </script> </head> <body bgcolor="white"> <f:view> <div id="main"> <h1><h:outputText value="#{Message.inputname_header}"/></h1> <h:messages style="color: red"/> <h:form id="helloForm"> <h:outputText value="#{Message.prompt}"/> <h:inputText id="userName" value="#{GetNameBean.userName}" required="true"> <f:validateLength minimum="2" maximum="20"/> </h:inputText> <h:commandButton onclick="gowait()" id="submit" action="#{GetNameBean.action}" value="Say Hello" /> </h:form> </div> <div id="wait" style="visibility:hidden; position: absolute; top: 0; left: 0"> <table width="100%" height ="300px"> <tr> <td align="center" valign="middle"> <h2>Please, wait...</h2> </td> </tr> </table> </div> </f:view> </body></html>

Page 74: JavaScript and Ajax

If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the form is just submitted. So, assign the id for your image and then add reload code that will be called after some short delay. For the example above, it might be:

<script>

function gowait() {

document.getElementById("main").style.visibility="hidden";

document.getElementById("wait").style.visibility="visible";

window.setTimeout('showProgress()', 500);

}

function showProgress(){

var wg = document.getElementById("waitgif");

wg.src=wg.src;

}

</script>

....

....

<img id="waitgif" src="animated.gif">

How to implement "Please, Wait..." page?

Page 75: JavaScript and Ajax

By using Java Script in your HTML code. The following Java Script is executed in the client side within your web

browser.

<SCRIPT type="text/javascript">

function displayWarningMessage() {

var answer = confirm("This process may take a while, please click 'OK' to continue.");

if (!answer){

return false;

}

else{

return disableSendBtton();

}

}

</SCRIPT>

How to get a pop-up window when clicking on a button?

Page 76: JavaScript and Ajax

What is Ajax

Asynchronous Java scripting Can also be used in synchronous

mode Also sometimes called as Remote

Scripting Integrated seamlessly with the

browser

Advantage: High Performance Web Based Applications

Page 77: JavaScript and Ajax

Ajax- Under the Hood…

Continued…

Page 78: JavaScript and Ajax

Ajax- Under the Hood

Uses JavaScript Engine Uses http/https protocol Uses http/https request / response

mechanism Runs in the address space of Browser Get the data, fires a http request Get and read the server response Render the required form area

Page 79: JavaScript and Ajax

Ajax- Possible Uses

Real time data validation Updating form data without the

refreshing / redrawing the page Background request – response Update page at specific intervals

e.g. Cricket Score board Possibilities are limitless Browser based desktop applications

Page 80: JavaScript and Ajax

Ajax- Browser Support

Popular browser like FireFox, Mozilla, Safari, Netscape and IE supports Ajax

Page 81: JavaScript and Ajax

Ajax- Who are using?

Gmail Google maps Web based Map applications Web based Business applications And many more…

Page 82: JavaScript and Ajax

Ajax- In Action

Conventional Approach When user requests for a page Browser re-renders the complete page

With Ajax Implemented Browser renders only the selection list

Page 83: JavaScript and Ajax

Ajax- Toolkits

Free Toolkits are available for ASP, .NET and JSP (dojo, prototype, jQuery toolkit)

But can be implemented without using any toolkit

Page 84: JavaScript and Ajax

Ajax Toolkits

Toolkits are function libraries written in JavaScript that can easily be used in your scripts

Each toolkit has its own strengths and weaknesses, so toolkits must be selected carefully

Each toolkit has its own learning curve and usage requirements

Popular toolkits are Dojo and jQuery

Page 85: JavaScript and Ajax

Ajax- The Inner Core

At the core of AJAX is xmlHttpRequest Object

This object is used To send a http request Get the server response

Like other objects this object too have its methods and properties

Continued…

Page 86: JavaScript and Ajax

Ajax- The Inner Core

Page 87: JavaScript and Ajax

xmlHttpRequest object

Method Description

abort() Stops/aborts the current request

send() Transmit the data/request

open() Opens a connection to the giver URL

getAllResponseHeaders() Returns the complete set of Headers

getResponseHeader() Returns the specified header value

Common xmlHttpRequest object Methods

Continued…

Page 88: JavaScript and Ajax

xmlHttpRequest object

Properties Description

onreadystatechanged Event handler for and event that fires at every state change

readyState Object’s current state (integer)

0=un-initialized

1=loading

2=loaded

3=interactive

4=complete

responseText String version of data returned by server

Common xmlHttpRequest object Properties

Continued…

Page 89: JavaScript and Ajax

responseXML DOM compatible document object of data returned by server

status Numeric code returned by the server

statusText String message related to status code

Common xmlHttpRequest object Properties

xmlHttpRequest object

Page 90: JavaScript and Ajax

Ajax- The Flow

Create the XMLHttpRequest Object Open the connection to server

object.open(method,url,sync-flag); Register the function for handling input

object.onreadystatechange=function; Send the data/request to the server

object.send(); Process the data

Get server data Parse if required Update the DOM (Display the result)

Page 91: JavaScript and Ajax

Brief Overview

Conventional Approach Request Response Refresh

AJAX Approach Request Response Refresh DOM

Web Application can behave like a native application

Page 92: JavaScript and Ajax

Thought is normally governed by requirement

A sayingLearning is simple

Implementation is not! Change in design as compared to

normal web application

Ajax- Thinking In!

Continued…

Page 93: JavaScript and Ajax

Uncover new ways to weave the web applications

The response that the application should send Simple string Complex XML

Ajax- Thinking In!

Page 94: JavaScript and Ajax

Hybrid application Application starts up like a normal web

application Uses AJAX some where in the successive web

pages e.g. Data reflection, Display morphing, Page

rearrangement Fully Ajax application

Application starts with AJAX Application uses AJAX through its life cycle

e.g. An editor

Ajax- Application Modes

Page 95: JavaScript and Ajax

<script language="javascript">function onAjaxCall(){

var url = "/clt/Specs/Specs?widget=saveCurrentSettings";//First step: create an instance//This is just a classical instance of class, but two options must be tried, for browser compatibility. if (window.XMLHttpRequest) // Object of the current windows{ req = new XMLHttpRequest(); // Firefox} else if (window.ActiveXObject) // ActiveX version{ req = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer }//Second step: wait for the responsereq.onreadystatechange = onSaveFilter;//Third step: make the request itself// open(mode, url, boolean): create a connection// mode: type of request, GET or POST// url: the location of the file, with a path.// boolean: true (asynchronous) / false (synchronous).// optionally, a login and a password may be added to arguments.// req.open("GET", "data.xml", true); // req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // req.send(null); req.open("POST", url, true);req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");// send: send a request to the server// null for a GET command.req.send( "&savePharamcyId=" + document.activeOrders.pharamcyId.value +

"&saveTeamId=" + document.activeOrders.teamId.value );}

Ajax- Example

Page 96: JavaScript and Ajax

function onSaveFilter(){

// States of readyState follow (only the last one is really useful):// 0: not initialized.// 1: connection established.// 2: request received.// 3: answer in process.// 4: finished. if (req.readyState == 4) {

//status//200 is OK//404 if the page is not found.if (req.status == 200) {

//alert('Success');// Filter values updated successfully.

}}

}</script>

..Contd

Page 97: JavaScript and Ajax

<body><script type="text/javascript"> // JavaScript function here ...</script><form name="myForm"> <h3>Simple Ajax Test</h3> <p>Input string: <input type="text" onkeyup="ajaxFunction(this.value);" name="username" /> </p> <p>Backwards: <em><span id="myElem"></span></em></p></form></body>

Example of HTML

97 JavaScript

Page 98: JavaScript and Ajax

<body><script type="text/javascript">function ajaxFunction(myStr) { var xmlHttp; try { ... } // end of try section xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById('myElem').innerHTML = xmlHttp.responseText; } } $path = "http://www.cs.kent.ac.uk/people/staff/amlf/"; xmlHttp.open("GET", $path + "reverse.php?str=" + myStr, true); xmlHttp.send(null); }</script></body>

The whole JavaScript function

98 JavaScript

Page 99: JavaScript and Ajax

Ajax- Example in ASP.NET

Page 100: JavaScript and Ajax
Page 101: JavaScript and Ajax
Page 102: JavaScript and Ajax
Page 103: JavaScript and Ajax
Page 104: JavaScript and Ajax

Thanks…