JavaScript and Ajax
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

JavaScript and Ajax

  • 5,228 views
Uploaded on

JavaScript ...

JavaScript
Ajax

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
5,228
On Slideshare
5,075
From Embeds
153
Number of Embeds
4

Actions

Shares
Downloads
282
Comments
0
Likes
8

Embeds 153

http://www.ustudy.in 113
http://ustudy.in 27
http://www.slideshare.net 11
http://www.masihkah.com 2

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. JavaScript and Ajax Mohan Bang
  • 2. Agenda: Conclusion and Summary 3 Ajax 3 2 JavaScript 1
  • 3. 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
  • 4.
    • 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
  • 5. Types of Scripting Language
    • JScript
    • ActionScript
    • ECMAScript
    • JavaScript
    • VBScript
  • 6. 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.
  • 7. 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.
  • 8. 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.
  • 9. 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.
  • 10. 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.
  • 11. 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=&quot;text/javascript&quot;> var test=&quot;http://www.test.com/Home page/&quot; document.write(encodeURI(test)+ &quot;<br />&quot;) </script> The output of the code above will be: http://www.test.com/Home%page/
  • 12. 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
  • 13. JavaScript compared to Java
  • 14. Overview on JavaScript Variable 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.
  • 15. 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”.
  • 16. 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”
  • 17. null Value This can be used with all JavaScript types. The “null” value indicates that a variable is un-initialized.
  • 18. 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.
  • 19. Escape characters Escape characters that can be used in JavaScript Tab t Backspace b New Line n Form Feed f Carriage Return r Backslash Double Quote ” Single Quote ’ Meaning Character
  • 20. 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 &quot;12&quot; 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.
  • 21. 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
  • 22. Operators
      • Assignment Operators
      • Comparison Operators
      • Arithmetic Operators
      • Logical Operators
      • String Operators
      • Bitwise Operators
      • Special Operators (typeof operator)
  • 23. Assignment Operators A = A – B A -= B A = A / B A /= B A = A* B A *= B A = A + B A += B What they imply Compound Assignment operators
  • 24. Comparison Operators R elational operators used for comparison and they return a logical value true or false based on the comparison. T he operands can be either numerical or string values. If left operand is less than or equal to right, expression results in a value true Less than or equal to (<=) If left operand is greater than or equal to right, expression results in a value true Greater than or equal to (>=) If left operand is less than right, expression results in a value true Less than (<) If left operand is greater than right, expression results in a value true Greater than (>) If the operands are not equal, the expression results in a value true Not equal to (!=) If operands are equal, the expression results in a value true. Equal (= =) Description Operator
  • 25. 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.
  • 26. Logical Operators Logical operators take Boolean values (true or false) as operands and returns a Boolean value. Returns false if the expression is true , and true if it is false Not ( ! ) !expr Returns true if either expr1 or expr2 is true or both else it returns false Or ( || ) expr1 || expr2 Returns true if both expr1 and expr2 are true else it returns false And ( && ) expr1 && expr2 Description Operator
  • 27. String Operators The string operator is used for string manipulation. JavaScript only supports string concatenation operator (+).
  • 28. 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)
  • 29. 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.
  • 30. 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.
  • 31. Special Operators (typeof operator) Suppose you define the following variables: var myFun = new Function(&quot;5+2&quot;) var shape=&quot;round&quot; var size=1 var today=new Date() The typeof operator returns the following results for these variables: typeof myFun is object typeof shape is string typeof size is number typeof today is object typeof dontExist is undefined
  • 32. 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
  • 33. 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);
  • 34. 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.
  • 35. Array Object Example <HTML> <HEAD> <TITLE> The Array Object </TITLE> </HEAD> <BODY> <BR><BR> <H1 ALIGN=&quot;CENTER&quot;> The Array Object </H1> <HR> <SCRIPT LANGUAGE = &quot;JavaScript&quot;> myArray=new Array(1,4,3,2,7,6,5,9,8,6,0) document.write(&quot;<PRE>&quot;) document.write(&quot;myArray.toString()t:tt&quot;) document.write(myArray.toString()+&quot;<BR>&quot;) document.write(&quot;myArray.join('-')t:tt&quot;) document.write(myArray.join(&quot;-&quot;)+&quot;<BR>&quot;) document.write(&quot;myArray.reverse()t:tt&quot;) document.write(myArray.reverse()+&quot;<BR>&quot;) document.write(&quot;myArray.sort()tt:tt&quot;) document.write(myArray.sort()+&quot;<BR>&quot;) document.write(&quot;</PRE>&quot;) </SCRIPT> </BODY> </HTML>
  • 36. The String Object Strings are declared using String() constructor var s = new String(); var s1=new String(“hello”);
  • 37. 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).
  • 38. String object Example <HTML> <HEAD> <TITLE> The String Object </TITLE></HEAD> <BODY> <BR><BR> <H1 ALIGN=&quot;CENTER&quot;> The String Object </H1><HR> <SCRIPT LANGUAGE = &quot;JavaScript&quot;> myString=new String(&quot;This is first string. This is second string&quot;) document.write(&quot;<PRE>&quot;) document.write(&quot;myString.toLowerCase()tt:&quot;) document.write(myString.toLowerCase()+&quot;<BR>&quot;) document.write(&quot;myString.toUpperCase()tt:&quot;) document.write(myString.toUpperCase()+&quot;<BR>&quot;) document.write(&quot;myString.substring(7)tt:&quot;) document.write(myString.substring(7)+&quot;<BR>&quot;) document.write(&quot;myString.substring(5,6)t:&quot;) document.write(myString.substring(5,6)+&quot;<BR>&quot;) document.write(&quot;myString.split('first')tt:&quot;) document.write(myString.split('first')+&quot;<BR>&quot;) document.write(&quot;myString.charAt(8)tt:&quot;) document.write(myString.charAt(8)+&quot;<BR>&quot;) document.write(&quot;myString.charCodeAt(1)tt:&quot;) document.write(myString.charCodeAt(1)+&quot;<BR>&quot;) document.write(&quot;myString.indexOf('first')t:&quot;) document.write(myString.indexOf('first')+&quot;<BR>&quot;) document.write(&quot;</PRE>&quot;) </SCRIPT> </BODY> </HTML>
  • 39. 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);
  • 40. 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.
  • 41. Boolean Object The Boolean object allows the creation of user defined boolean values.
  • 42. 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>
  • 43. 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 constant LOG2E The base 2 logarithm of e   LN2 The natural logarithm of 2
  • 44. 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
  • 45. Global Object The Global object provides methods, which can be accessed globally.
  • 46. 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.
  • 47. 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.
  • 48. 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.
  • 49. JavaScript Event
  • 50. JavaScript and Object Oriented Programming JavaScript is an excellent scripting language to write object oriented web applications. Example: <script language=&quot;javascript&quot; type=&quot;text/javascript&quot;> <!-- person = new Object() person.name = &quot;Tim Scarfe&quot; person.height = &quot;6Ft&quot; timObject = { property1 : &quot;Hello&quot;, property2 : &quot;MmmMMm&quot;, property3 : [&quot;mmm&quot;, 2, 3, 6, &quot;kkk&quot;], method1 : function(){alert(&quot;Method had been called&quot; + this.property1)} }; timObject.method1(); alert(timObject.property3[2]) // will yield 3 //--> </script>
  • 51. 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.
  • 52. 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
  • 53. Document Object Model (DOM)
    • Introduction
    • DOM Implementation
    • DOM with JavaScript
    • Setup
    • DOM Components
    • Creating Nodes
    • Traversing the DOM
    • Outline
    We will discuss about …
  • 54. 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.
  • 55. XML Document Object Model (DOM)
    • W3C standard recommendation
    • Build tree structure in memory for XML documents
    • DOM-based parsers parse these structures
    • Exist in several languages (Java, C, C++, Python, Perl, etc.)
  • 56. Representing Document as a tree DOM tree Each node represents an element, attribute, etc. <?xml version = &quot;1.0&quot;?> <message > <from>Paul</from> <to>Tim</to> <body>Hi, Tim!</body> </message> from body “ Hi, Tim!” Document to Tim Paul
  • 57. Node created for element message Element message has child nodes for body,to and from element Element body has child node for text &quot;Hi, Tim!“ ..
  • 58. Interfaces The Node interface - defines properties and methods for traversing and manipulating the tree Properties: childNode,firstChild,lastChild Methods : appendChild( ), removeChild( ), replaceChild( ), and insertBefore( )
  • 59. Types of nodes Interface Element Text Document Comment DocumentFragment Attr nodeType constant Node.ELEMENT_NODE Node.TEXT_NODE Node.DOCUMENT_NODE Node.COMMENT_NODE Node.DOCUMENT_FRAGMENT_NODE Node.ATTRIBUTE_NODE
  • 60. 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.
  • 61. Core DOM Node Document CharacterData Element Attribute Text Comment
  • 62. DOM Implementations
    • DOM-based parsers
      • Microsoft’s msxml
      • Sun Microsystem’s JAXP
  • 63. 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 .
  • 64. DOM and JavaScript
    • We use JavaScript and msxml parser
    • XML document marks up article
    • Use DOM API to display document’s element names/values
  • 65. Article marked up with XML tags. 1 <?xml version = &quot;1.0&quot; ?> 2 3 <!-- Fig. 8.2: article.xml --> 4 <!-- Article formatted with XML --> 5 6 <article> 7 8 <title> Simple XML </title> 9 10 <date> December 6, 2000 </date> 11 12 <author> 13 <fname> Tem </fname> 14 <lname> Nieto </lname> 15 </author> 16 17 <summary> XML is pretty easy. </summary> 18 19 <content> Once you have mastered HTML, XML is easily 20 learned. You must remember that XML is not for 21 displaying information but for managing information. 22 </content> 23 24 </article>
  • 66. Traversing article.xml with JavaScript. 1 <!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; 2 &quot;http://www.w3.org/TR/html4/strict.dtd&quot; > 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 = &quot;text/javascript&quot; language = &quot;JavaScript&quot; > 16 17 var xmlDocument = new ActiveXObject( &quot;Microsoft.XMLDOM&quot; ); 18 19 xmlDocument.load( &quot;article.xml&quot; ); 20 Element script allows for including scripting code Instantiate Microsoft XML DOM object Load article.xml into memory; msxml parses article.xml and stores it as tree structure
  • 67. Traversing article.xml with JavaScript. (Contd..) 21 // get the root element 22 var element = xmlDocument.documentElement; 23 24 document.writeln( 25 &quot;<p>Here is the root node of the document:&quot; ); 26 document.writeln( &quot;<strong>&quot; + element.nodeName 27 + &quot;</strong>&quot; ); 28 29 document.writeln( 30 &quot;<br>The following are its child elements:&quot; ); 31 document.writeln( &quot;</p><ul>&quot; ); 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( &quot;<li><strong>&quot; + curNode.nodeName 39 + &quot;</strong></li>&quot; ); 40 } 41 42 document.writeln( &quot;</ul>&quot; ); 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 )
  • 68. Traversing article.xml with JavaScript. (Contd..) 47 document.writeln( &quot;<p>The first child of root node is:&quot; ); 48 document.writeln( &quot;<strong>&quot; + currentNode.nodeName 49 + &quot;</strong>&quot; ); 50 document.writeln( &quot;<br>whose next sibling is:&quot; ); 51 52 // get the next sibling of first child 53 var nextSib = currentNode.nextSibling; 54 55 document.writeln( &quot;<strong>&quot; + nextSib.nodeName 56 + &quot;</strong>.&quot; ); 57 document.writeln( &quot;<br>Value of <strong>&quot; + nextSib.nodeName 58 + &quot;</strong> element is:&quot; ); 59 60 var value = nextSib.firstChild; 61 62 // print the text value of the sibling 63 document.writeln( &quot;<em>&quot; + value.nodeValue + &quot;</em>&quot; ); 64 document.writeln( &quot;<br>Parent node of &quot; ); 65 document.writeln( &quot;<string>&quot; + nextSib.nodeName 66 + &quot;</strong> is:&quot; ); 67 document.writeln( &quot;<strong>&quot; + nextSib.parentNode.nodeName 68 + &quot;</strong>.</p>&quot; ); 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 )
  • 69. Traversing article.xml with JavaScript.
  • 70. 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.
  • 71. Memory Leaks A 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.
  • 72. JavaScript in Projects How to implement &quot;Please, Wait...&quot; 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 &quot;Wait&quot; DIV. You can customize the look-n-fill with CSS if you like.
  • 73. Example: <%@ taglib uri=&quot;http://java.sun.com/jsf/html&quot; prefix=&quot;h&quot; %> <%@ taglib uri=&quot;http://java.sun.com/jsf/core&quot; prefix=&quot;f&quot; %> <f:loadBundle basename=&quot;demo.bundle.Messages&quot; var=&quot;Message&quot;/> <html> <head> <title>Input Name Page</title> <script> function gowait() { document.getElementById(&quot;main&quot;).style.visibility=&quot;hidden&quot;; document.getElementById(&quot;wait&quot;).style.visibility=&quot;visible&quot;; } </script> </head> <body bgcolor=&quot;white&quot;> <f:view> <div id=&quot;main&quot;> <h1><h:outputText value=&quot;#{Message.inputname_header}&quot;/></h1> <h:messages style=&quot;color: red&quot;/> <h:form id=&quot;helloForm&quot;> <h:outputText value=&quot;#{Message.prompt}&quot;/> <h:inputText id=&quot;userName&quot; value=&quot;#{GetNameBean.userName}&quot; required=&quot;true&quot;> <f:validateLength minimum=&quot;2&quot; maximum=&quot;20&quot;/> </h:inputText> <h:commandButton onclick=&quot;gowait()&quot; id=&quot;submit&quot; action=&quot;#{GetNameBean.action}&quot; value=&quot;Say Hello&quot; /> </h:form> </div> <div id=&quot;wait&quot; style=&quot;visibility:hidden; position: absolute; top: 0; left: 0&quot;> <table width=&quot;100%&quot; height =&quot;300px&quot;> <tr> <td align=&quot;center&quot; valign=&quot;middle&quot;> <h2>Please, wait...</h2> </td> </tr> </table> </div> </f:view> </body> </html>
  • 74. If you want to have an animated gif of the &quot;Wait&quot; 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(&quot;main&quot;).style.visibility=&quot;hidden&quot;; document.getElementById(&quot;wait&quot;).style.visibility=&quot;visible&quot;; window.setTimeout('showProgress()', 500); } function showProgress(){ var wg = document.getElementById(&quot;waitgif&quot;); wg.src=wg.src; } </script> .... .... <img id=&quot;waitgif&quot; src=&quot;animated.gif&quot;> How to implement &quot;Please, Wait...&quot; page?
  • 75. By using Java Script in your HTML code. The following Java Script is executed in the client side within your web browser. <SCRIPT type=&quot;text/javascript&quot;> function displayWarningMessage() { var answer = confirm(&quot;This process may take a while, please click 'OK' to continue.&quot;); if (!answer){ return false; } else{ return disableSendBtton(); } } </SCRIPT> How to get a pop-up window when clicking on a button?
  • 76. 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
  • 77. Ajax- Under the Hood… Continued…
  • 78. 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
  • 79. 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
  • 80. Ajax- Browser Support
    • Popular browser like FireFox, Mozilla, Safari, Netscape and IE supports Ajax
  • 81. Ajax- Who are using?
    • Gmail
    • Google maps
    • Web based Map applications
    • Web based Business applications
    • And many more…
  • 82. 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
  • 83. Ajax- Toolkits
    • Free Toolkits are available for ASP, .NET and JSP (dojo, prototype, jQuery toolkit)
    • But can be implemented without using any toolkit
  • 84. 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
  • 85. 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…
  • 86. Ajax- The Inner Core
  • 87. xmlHttpRequest object Common xmlHttpRequest object Methods Continued… Transmit the data/request send() Opens a connection to the giver URL open() Stops/aborts the current request abort() Description Method Returns the specified header value getResponseHeader() Returns the complete set of Headers getAllResponseHeaders()
  • 88. xmlHttpRequest object Common xmlHttpRequest object Properties Continued… Object’s current state (integer) 0=un-initialized 1=loading 2=loaded 3=interactive 4=complete readyState String version of data returned by server responseText Event handler for and event that fires at every state change onreadystatechanged Description Properties
  • 89. xmlHttpRequest object Common xmlHttpRequest object Properties Numeric code returned by the server status String message related to status code statusText DOM compatible document object of data returned by server responseXML
  • 90. 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)
  • 91. Brief Overview
    • Conventional Approach
      • Request
      • Response
      • Refresh
    • AJAX Approach
      • Request
      • Response
      • Refresh DOM
    • Web Application can behave like a native application
  • 92.
    • Thought is normally governed by requirement
    • A saying
      • Learning is simple Implementation is not!
    • Change in design as compared to normal web application
    Ajax- Thinking In! Continued…
  • 93.
    • Uncover new ways to weave the web applications
    • The response that the application should send
      • Simple string
      • Complex XML
    Ajax- Thinking In!
  • 94.
    • 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
  • 95. <script language=&quot;javascript&quot;> function onAjaxCall() { var url = &quot;/clt/Specs/Specs?widget=saveCurrentSettings&quot;; //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(&quot;Microsoft.XMLHTTP&quot;); // Internet Explorer } //Second step: wait for the response req.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(&quot;GET&quot;, &quot;data.xml&quot;, true); // req.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); // req.send(null); req.open(&quot;POST&quot;, url, true); req.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); // send: send a request to the server // null for a GET command. req.send( &quot;&savePharamcyId=&quot; + document.activeOrders.pharamcyId.value + &quot;&saveTeamId=&quot; + document.activeOrders.teamId.value ); } Ajax- Example
  • 96. 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
  • 97. Thanks…