Your SlideShare is downloading. ×
  • Like
JavaScript and Ajax
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

JavaScript and Ajax


JavaScript …


Published 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


Total Views
On SlideShare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. JavaScript and Ajax Mohan Bang
  • 2. Agenda: Conclusion and Summary 3 Ajax 32 JavaScript1
  • 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="text/javascript"> var test=" page/" document.write(encodeURI(test)+ "<br />") </script> The output of the code above will be:
  • 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 JavaScript Java 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.
  • 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 Character Meaning ’ Single Quote ” Double Quote Backslash r Carriage Return f Form Feed n New Line b Backspace t Tab
  • 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 "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.
  • 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 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
  • 24. 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.
  • 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. 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
  • 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 Operato r 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- propagati ng 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("5+2") var shape="round" 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="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:tt") document.write(myArray.toString()+"<BR>") document.write("myArray.join('-')t:tt") document.write(myArray.join("-")+"<BR>") document.write("myArray.reverse()t:tt") document.write(myArray.reverse()+"<BR>") document.write("myArray.sort()tt:tt") document.write(myArray.sort()+"<BR>") document.write("</PRE>") </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="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()tt:") document.write(myString.toLowerCase()+"<BR>") document.write("myString.toUpperCase()tt:") document.write(myString.toUpperCase()+"<BR>") document.write("myString.substring(7)tt:") 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')tt:") document.write(myString.split('first')+"<BR>") document.write("myString.charAt(8)tt:") document.write(myString.charAt(8)+"<BR>") document.write("myString.charCodeAt(1)tt:") document.write(myString.charCodeAt(1)+"<BR>") document.write("myString.indexOf('first')t:") document.write(myString.indexOf('first')+"<BR>") document.write("</PRE>") </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 Attribute The event occurs when... onabort Loading of an image is interrupted onblur An element loses focus onchange The content of a field changes onclick Mouse clicks an object ondblclick Mouse double-clicks an object onerror An error occurs when loading a document or an image onfocus An element gets focus onkeydown A keyboard key is pressed onkeypress A keyboard key is pressed or held down onkeyup A keyboard key is released onload A page or an image is finished loading onmousedown A mouse button is pressed onmousemove The mouse is moved onmouseout The mouse is moved off an element onmouseover The mouse is moved over an element onmouseup A mouse button is released onreset The reset button is clicked onresize A window or frame is resized onselect Text is selected onsubmit The submit button is clicked onunload The user exits the page
  • 50. 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() = "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>
  • 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 = "1.0"?> <message > <from>Paul</from> <to>Tim</to> <body>Hi, Tim!</body> </message> from body “Hi, Tim!” Document to TimPaul
  • 57. 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!“ ..
  • 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 XML4J IBM’s XML Parser for Java (XML4J) is available at no charge from Xerces Apache’s Xerces Java Parser is available at no charge from 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 4DOM 4DOM is a parser for the Python programming language and is available at no charge from XML::D OM XML::DOM is a Perl module that we use in Chapter 17 to manipulate XML documents using Perl. For additional information, visit
  • 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 = "1.0"?> 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 "-//W3C//DTD HTML 4.01//EN" 2 ""> 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 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 "<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)
  • 68. 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)
  • 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 "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.
  • 73. Example: <%@ taglib uri="" prefix="h" %> <%@ taglib uri="" 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>
  • 74. 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?
  • 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="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?
  • 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 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…
  • 88. 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…
  • 89. 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
  • 90. Ajax- The Flow  Create the XMLHttpRequest Object  Open the connection to server ,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="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 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. //"GET", "data.xml", true); // req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // req.send(null);"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
  • 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…