0% found this document useful (0 votes)
118 views50 pages

Untitled

Uploaded by

Pranav Moghe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
118 views50 pages

Untitled

Uploaded by

Pranav Moghe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 50
Web Scripting CHAPTER 2 Languages University Prescribed Syllabus. JavaScript + Introduction to Seripting lan, Variable Scopes, JS Data Types, JS Functio ‘guages, Introduction to JavaScript (JS), IS Variables and Constants, JS ms, IS Array, JS Object, IS Events, Advanced JavaScript : JSON ~ ISON Create, Key-Value Pair, JSON Access, SON Array, JS Arrow Functions, JS Callback Functions, JS Promises, JS Asyne-Await Functions, JS Error Handling, AJAX: Why AJAX, Call HTTP Methods Using AJAX, Data Sending, Data Receiving, AJAX Error Handling, JQUERY : Why JQuery, How to Use, DOM Manipulation with Quer Design Using JQuery Dynamic Content Change with JQuery, UL 21. Introduction to Scripting Languages 2-3 2.1.1 Advantages of Scripting Languages 2-3 2.1.2 Application of Scripting Languages. 23 22 Introduction to JavaScript 2:3 221 Features of JavaScript 24 222 Applications of JavaScript 24 22:3 Characteristics of JavaScript 24 22.4 Advantages and Disadvantages of Client- Side Scripting 24 228 Differences between Client Side and Server Side Scripting Language 25 22.6 Using JavaScript in an HTML Document. 25 22.7 JavaScript Example 25 23 JavaScript Variables and Constants, 26 23.1 Variables 126 2.3.2 JavaScript Constants 27 24 JS Variable Scopes. 27 25 JS Data Types 29 28 JS Functions: 2-10 281 Function Definition m0 262 Defining Function Arguments. any 263 Defining a return statement. 244 rt (SPPU-Sem 6-7) 27 JS Arey 27.1, Derent ways 1 create an AY 23 Array Methods: Inerating Through an Array ao Daieting Element from an Arey ae Array Method Spioe() “ pe JaveaSonst Onects ™ 281 Creating Otyects in JavaSerOt es ay 282 Sting Object 283 Regexp Odyect - . 254 Math Odject 285 Date Object 286 Number Object 287 Array Object 29 JS Events 2.10 Advanced JavaSonpt: JSON 2.11. JSON Data Types 2.12 JSON Object 2.13. JS Arrow Functions 2.14 JS Caliback Functions 2.18 JaveSorit Promise 2.16 JS Asyne-Awalt Functons 2.17 JS Error Handing. 218 AJAX. sre 2.18.1 Asynchronous in AJAX 2.18.2 Benefits of Ajax 2183 2184 2.18 AJAX Design Bases = 219.1 AJAX Processing Steps 220 Call HTTP Methods Using AJAX 221 AJAX Error Handling 2.22 JQUERY 2201 Features of jQuery 2222 — Loading jQuery. 2223 Selecting Elements 223 DOM Manipulation wit JQuery 2.23.1 Changing Styles 2.732 — Creating and Appending Elements 2.233 Removing Elements 2.24 Dynamic Content Change with JQuery, 2.25 UI Design Using Jquery Chapter Ends (New Syllabus wef academic year 2021-22) (6-57) HIN oan 5 fl Tech-Neo Publications .A SAC \ web Application Development (SPPU-Sem 6-1) (ihsb Govtoang Languages) Pg. Noi (2-3 ———_—— -1_ INTRODUCTION TO SCRIPTING » LANGUAGES amming languages The scripting language is basically a language where instructions are written for a nun time environment. They do ot roquite the compilation step and are rather interpreted. It tings ew functions to applications and glue complex system together. A scripting language is a programming language designed for integrating and communicating with csher programming languages. ‘There are many scripting languages some of them are discussed below 1, Bash : It is a scripting language to work in the Linux interface. It is a lot easier to use bash to create scripts than other programming languages. It describes the tools to use and code in the command line and create useful reusable scripts and conserve documentation for ther people to work with. 2 Node js : It is a framework to write network applications using JavaScript. Corporate users of Node,js include IBM, LinkedIn, Microsoft, Netflix, PayPal, Yahoo for real-time web applications. 3. Ruby : There are a lot of reasons to leam Ruby programming language. Ruby's flexibility has allowed developers to create innovative software. It is a scripting language which is great for web development. 4. Python : It is easy, free and open source. It supports procedure-oriented programming and object-oriented Programming. Python is an interpreted language with éynamic semantics and huge lines of code are scripted and is currently the most hyped language among evelopers S. Perl : A scripting language with innovative features to ‘make it different and popular. Found on all windows ‘and Linux servers, It helps in text manipulation tasks. High traffic websites that use Perl extensively include Priceline.com, IMDB. °S 2.1.1 Advantages of Scripting Languages (1) Easy learning : The user can lear to code in scripting languages quickly, not much knowledge of web technology is required (2) Fast editing : It is highly efficient with the limited ‘umber of data structures and variables to use. (3) Interactivity: 1 helps in adding faces and combinations in web pages. Modern web Pages demand the use of scripting languages. To create enhanced web pages. visualization fascinated visual description, Which includes background and foreground colors and (4) Functionality : There are different libraries which are part of different scripting languages. They help in creating new applications in web browsers and are different from normal programming languages. 2.1.2 Application of Scripting Languages Scripting languages are used in many areas: 1. Scripting languages are used in web applications. It is used in server side as well as client side. Server side scripting languages are: JavaScript, PHP, Perl etc. and client side scripting languages are: JavaScript. AJAX. JQuery ete 2. Scripting languages are used in system administration For example: Shell, Perl, Python scripts etc. 3. _Itis used in Games application and Multimedia. 4. It is used to create plugins and extensions for existing applications. 1_2.2__ INTRODUCTION TO JAVASCRIPT GQ. Write a short note on JavaScript. 7 © JavaScript isa light-weight object-oriented programming language which is used by several websites for scripting the webpages. ‘© JavaScript was developed by Mr. Brendan Eich in 1995 who was working in Netscape. © JavaScript is not a compiled language, but it is a translated language. © The JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web browser. + Its an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML document ‘© JavaScript helps to make our webpage more lively and imeractive. JavaScript is widely used in mobile application development as well as in game development ‘© JavaScript was initially called as LiveScript and later oon the name is changed to JavaScript (New Syllabus wes academic year 2021-22) (P6-57) Talrecn Neo Pubicatons A SACHIN SHAH Verne 0 PO.No. (24 Web Application Development (SPPI Sin) fr input is validated before ing th he Page © With JavaScript, users can build modern web a wer This minimizes the server wane o applications to interact directly without reloading the set ewer Toads on the server ich page every time. The traditional website uses JS (© provide several forms of interactivity and simplicity 2.2.1 Features of JavaScript ‘The features of JavaScript areas follows’ 1. All popwlar web browsers support JavaScript as they provide built-in execution environments 2. JavaScript follows the syntax and structure of the C programming language, Thus, it is a structured programming language. 3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation 4. JavaScript is an object-oriented programming langu that uses prototypes rather than using classes for inheritance. Iti a light-weighted and interpreted language. Iis a case-sensitive language. JavaScript is supportable in several operating systems including Windows, macOS, ete. 8. It provides good control to the users over the web browsers ‘YS 2.2.2 Applications of JavaScript JavaScript is used (0 create interactive websites. It is ‘mainly used for: Client-side validation, Dynamic drop-down menus, Displaying date and time, Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box), 5. Displaying clocks, ete. 2.2.3. Characteristics of JavaScript 1. JavaScript is a lightweight, interpreted client-side scripting language. 2. Designed for developing network-based applications. 3. JavaScript is complementary to Java, 4. JavaScript is complementary to and integrated with HTML. I is an open source and cross-platform, 3. May need more time and effort for develop scripts are not already available thr resources 4 (New Syllabus we f academic year 2021-22) (P6-57) (Web Scripting Languages) 7. Thais monet fre ETOWAH SE ong has been forgotten to enter nerve iterfaes cam Be STEEL, Which cay 9, responses to end User actions HIKE MOUSE oF faye ‘ ar tivities 9, JavaScript cam include elements lke dap ga, components and sliders (0 provide a feel of gcp interface to the users. ys 2.2.4 Advantages and Disadvantages of Client- Side Scripting TGQ.” “What are the advantages and disadvanta 1 cient side scripting? E Advantages of Client- Side Scripting 1. Immediate response to a user's actions which, more interactivity No need to go to the server: hence, execution is f Improve the usability of web sites for users browsers support scripts, 4. Developers get_more control over the look behaviour of their web widgets, 5. Possible to substitute by HTML if a user's browsers ‘not support scripts. 6. Are reusable and obtainable from various types of resources. Disadvantages of Client- Side Scripting |. Scripts are not supported by all of the browsers he errors might occur if no alternatives have provided. ‘There is need of more quality assurance te different browsers and browser Versions SUP dierent Sometimes, the web widget looks i ‘control, but their behaviour may be diff Yersa, which may lead to usability problet e) Badrecnneo Publications A SACHIN. web Apoication Development (SPPU-Som 6-17) ferences between Client Side and Server Side Scripting Language GR What are the server side scripting language? we 22. Client Side Scripting Language The client side script is executed by web browser which is located at the user's ‘computer. Server Side Scripting Language ‘The server side script is executed by the Web Server ‘outputs Which is to be sent to the browser. Client side scripting language cannot connect tthe databases which is located on the web server. Taba Server side seripting language can connect and access to the databases which is, located on the web server. Client side scripting language cannot have access to the file system which is located on the web File System Server side seripting language has access to the file system which is located on the web server. Samet we sabi | poate perme Caer Client side scripting language can access the files and settings that are local at the user's computer. ‘Access to Setting User cannot block the Server side scripting language Response from a server-side script slow since the scripts are processed on the remote computer. PHP, JSP, ASP, ASP.Net, Ruby, Perl, etc. User can block the Client side scripting language Response from a client-side script is quick since the seripts are processed on the local computer. JavaScript, VBScript, ete. Examples 6 Using JavaScript in an HTML Document * The code (script) of JavaScript is written in the script ‘opening HTML tags in a web page. Usually, the © The W. 2.2.7 JavaScript Example > 1. Embedded JavaScript ‘The JavaScript code can be embed into a HTML file using the tag JavaScript <htitle> <script language="TavaScript"> document.write("Weleome To JavaScrip </script> <head> <body> </body> </html> document.write ‘This method writes a string into HTML document. Teal rech-Neo Pubications.A SACHIN SHAH Venture Web Application Development (SPPU-Sem 6.11) Output © 0 msn i c File | CAkersvAdminyDesktoprsamplet hint Weloome To JavaScript In the above program, outside the <script> element, the HTML tags can be used in their normal way, but if we want to use the HTML tags in <script> section, then document write() method is used. Program 22.1 : Write a program to demonstrat line break example, <huml> <head> <itille> JavaScript <hitle> <head> color="blue"> <écript type="texvJavaScript"> document.write("Welcome To JavaScript"); document.write("<br>Line break’); </scxipt> </font> </body> </btml> output BD meson x + | | GC Otel CsersiAdmin/Destop/somlet2 hr | |Welcome To JavaScript | Line break | 2. External JavaScript “An external JavaScript file can be created to embed it in many html pages. It suppor the concept of code reusability as single (web Scripting Languages) Fxample external JavaScript code demonstrating welco message MyFileds function mse) alent("Weleome To The World of Web"): } HTML page <himl> <head> <script langusee= </script> </head> syavsSeript”sro="MyFileje'> <body> <ep> Welcome to JavoSeript </P7 <form> <input type="be onclick ="msg0"!> </form> </body> </html> stytton”value="Click Here" Output t= “eS © omivenime 2.3 JAVASCRIPT VARIABLES AND CONSTANTS Y 2.3.1 Variables here We ‘© Variable is a name given to memory location the dat can store some value. The value depends upon type of the variable. ‘© In JavaScript there are number of d store different types of values. These dat primarily categorized as > 1, JavaScript primitive data types ata types use! pes JavaScript file can be embed into several htm! pages. aw ‘An external JavaScript file is saved by the extension In JavaScript, there are five types of primitive “js” types as follows suanven™® {New Syllabus wee academic year 2021-22) P6-57) oy TBrech-neo Publications -A SACHIN (Web Scripting Languages) ..Pg. No. (2-7) Represents numeric values eg, 13 Represents Boolean rao le maori —Pimietnea[ Represens snp [xa | Rerocas mat mee eae all __t——_-—_______ | Output 1D omy « GO Hie | CAtmaiAdmavDesktop/sape'2 htm Rolino : 22 Name : Vennu %. 2.5.2 JavaScript Constants © The const keyword was also introduced in the wraScript non-primitive data bee alle! ES6(ES2015) version o create constants. For example, $e No. | Data Type Description const x = 5; 1, | Object | Represents instance which helps wo J * Once a constant is initialized, we cannot change its access members value const x = 5; 8 Represents set of same value ne 2_| Amey = * = 10; // Error! constant cannot be changed. [3 [Reatxp [Represents regular expression atalngt) «+ JavaScript is considered as a dynamic type language that is there is no need to specify type of the variable. This type is dynamically decided by the JavaScript engine, While declaring a variable, “var” keyword is used on place of data type. Var means variant, that is the variable can store any type of value like numbers, strings, dates etc Examples 1. yarmo= 101; ‘Molding number 2. varsname="Shraddha"; ‘Mbolding string Program 2.3.1 : To display roll no. and name of student sing “vat” keyword <til> <head> stile> Data Types <itile> <head> <body> ‘eri language="JavaScript"> font size=5 color=blue>"); varmo = 22, ‘arene = "Venu"; tbeunentwrite("Rollno :"+rn0}: document. write("<be>Name :"-+sname): beument write(*</font>"); Sieript> <tbody> * Simply. a constant is a type of variable whose value ‘cannot be changed Also, you cannot declare a constant without initializing it. For example, ‘const x; // Error! ing initializer in const declaration. ‘console-log(x) ————— Di 2.4 JS VARIABLE SCOPES eee eee © Scope refers to the availability of variables and functions in certain parts of the code. In JavaScript, a variable has two types of scope: (1) Global Scope (2) Local Scope 1. Global Scope A variable declared at the top of a program or outside of a function is considered a global scope variable. Program 2.4.1 : Example of a global scope variable » 1 program to print a text let a= "hello"; function greet ){ console.log(a); } ‘tom > greet():// hello new abs we academic year 2021-22) (P6-57) [ed rect-Neo Publications .A SACHIN SHAH Venture Web Application Development (SPPU-Sem 6-17) Twin the above program, variable a is declared atthe top lable, It means the of a program and is a global ¥: Saniable a can be used anywhere in the program. “sThe valve of a global variable can be changed inside 2 function. For example. ble J program to show the change in global va eta = "hello": fanction greet) ( =3; before the function call ‘console-log(s}; Jeter the function call sweets console toga)! 3 aie te above program, variable ais global variable wae of en belo, Then to varale ai ete jneide a function and the value changes 10 3+ «ence the value ofa changes after changing it inside the function. sTn JavaScript, @ variable can also be used wiet! se vne i Ifa variable i used without declaring eclvanabl automatically becomes 8 global variable © Forexample, function gret0 { a= “bello” > greet console Jog(as // hello win the above program, variable ais a global variable. “Sif the variable was declared using Jet a = “hello”, the program would throw an error. > 2, Local Scope ‘sAvvariable can also have a local scope, ie it can only be accessed within a function. Program 2.42 : Local Scope Variable 1 program showing local scope ofa variable det a = "bello": Sanction greet() { letb = "World" console logla +b): (New Syllabus we, academic year 2021-22) (P6-57) ) greets tconsole.Jog(a + bs /! e770 output helloWarld ncaught ReferenceErTor si . 1 above program i one tor ate Te sees uo access variable P iputside of the Function, aq error occurs tet is Block Seoped «block scoped (variable cam be sy in de immediate BIOCK) eR ‘program 2.43: Biock-scoped Variable Tr pmgam sowing blockseoPed concept 1) global variable leta= Hello: function greet) {local variable Jerb = "Worlds eonsoledog(a +'' +b): if (b == World) { I block-scoped variable ete = ‘hello console.log(a +''+b+'' +e): c I[ variable c cannot be accessed here consoleclog(a +'' + b-+'' + 0); } greet(); Output Hello World Hello World hello Uncaught ReferenceEror: ¢is not defined Inthe above program, variable / et! Tal rech-neo Pubsications -A ACH sw Development (SPF web Application Development (SPPU-Sem 6.17) (Web Scripting Languages) ...Pg. No. (2-9) is a global variable. It can be accessed anywhere in the program. pis a local variable. It can be accessed only inside the function greet isa block-scoped variable, It can be accessed only inside the if statement block. Hence, in the above program, the first two console log() Work without any issue. However, We are trying to access the block-scoped saiable c outside of the block in the third console.log(), ‘his wll throw an error. ———ee 41a 2.5 JS DATA TYPES Data types in JavaSoript 1. Primitive Fig. 2.5.1 : Data types in JavaScript + Variable is a name given to memory location where we can store some valve. The value depends upon the data type of variable + In JavaScript there are number of data types used to store different types of values. These data types are primarily categorized as > 1, JavaScript primitive data types In JavaScript, there are five types of primitive data types as follows > 2. JavaScript non-primitive data types Sr. | Data Type Description No. 1. | Object. Represents instance which helps to access members 2__| Array: Represents set of same values 3._[ RegExp | Represents regular expression ‘* JavaScript is considered as a dynamic type language that is there is no need to specify type of the variable. © This type is dynamically decided by the JavaScript engine. While declaring a variable, “var keyword is used on place of data type. Var means variant, that is the variable can store any type of value like numbers, strings, dates ete Examples ‘Molding number ‘Molding string 1. varmo= 101; 2. var sname="Kun: Program 2.8.1 : Write a program to display roll no. and name of student using “var” keyword. <html> <head> <title> Data Types </itle> </head> <body> <script language="JavaScript"> document write("<fon site=5 color=blue>"); var mo = 101; Se] Data Description varsname = "Kunal: No. | Type document.write("Rollno : "-+mno); “ document.write("<br>Name :"+sname); 1. [Sting | Represents sequence of characters ; “ | eg. “Ishita” document.write("</foat>"); 2 | valves e.g. 101 | | </sesP> 2. [Number | Represents numeric values ane 3. | Boolean | Represents Boolean valve either) | oa), true or false | 4. | Undefined | Represents undefined value 5) Null Represents null means no value at all (New Sylabus wef academic year 2021-22) (P6-S7) Tech-Neo Publications ..A SACHIN SHAH Venture Web Application Development (SPPU-Sem 6) Program 2.5.2 : Write a JavaScript to take 2 digit umber soreie Serine and then separate these 2 digits, then multiply first digit by itself for second digit times. (for example, 23 should be separated as 2 and 3. 2 should multiply with itself 3 tims. <biml> <head> <title> JavaScript<ititle> <head> <body> <font size=5> document.write("Entered number is :" + num +"<be/>") var quat=parselnt(num/10); var result =Math.powquat, rem): document.write(quat+" multiplied itself -+rem+" times "+ result); </script> </font> </body> </hal> Output D eascpt © & Osewicsnm | | | | Entered number is :43 4 multiplied itself 3 times : 64 i." Eipain "ser “defined function in lavaScrigt with + ‘ suitable example. ; Function helps to avoid repetition of code and wnte ‘modular codes. A program can be divided into small and manageable modules called as functions. | Just like the other programming languages such as C, C++ and Java, the function concept with all its features is supported by JavaScript We can create our own functions known as user defined functions. (Web Scripting Languages) ...Pg. No. (2-19) 3 2.6.1 Function Definition In JavaScript, a function is defined by using gy function keyword, followed by name of function parameters list optional]. and a statement block inside cu, braces Syntax script type="text javascript"> function fuvetion_name({parameter-list} { Statements: ) </script> [= program to display hello message using function call <huml> <head> <title> Functions <!title> </head> <body> ‘<script language "JavaScript" > Function callMe() { alert ("Hello"); d cealMe(); </script> ‘</body> </html> ‘5 Calling a function on click event of a button <humi> <head> <ttle> Functions <fitle> | Sseript language ="JaraSeript"> | funetion callMe() (New Syllabus we f academic year 2021-22) (6-57) Tech-Neo Publications A SACHIN SHAH Ve"™* wen Application Development (SPPU-Sem 6.17) { e der Hello")s <<iscti> </head™ <td> font siz0=5> ‘<p> Click the following button to call the function</p> form? <input type= "button onClick="callMe();" value: Hell" om? <at> <fdy> <html> "Say (0 Oc cick following button to espe % 2.6.2 Defining Function Arguments + While defining a function, we can declare variables in the header statement of the function. These variables ‘are known as parameters or formal arguments ‘+ When this function gets called, we can pass values for these variables. These values are known as arguments or actual arguments. (Web Scripting Languages) ..Pg. No. (2-11) <body> <font size=5> <p>Click the following button to all the function</p> <form> <input type="button" onClick="add(10,20):" value="Click Here"> </form> </font> </body> </html> Output Bea © Oise Click the following butn to Tepes % 2.6.3 Defining a return statement © In JavaScript function we can have return statement which is optional. This helps to return a value from a function. This statement is written at the last in a function. * The retuned value goes to the location where the function is called GQ_ Write a program which will accept two numbers as ‘arguments and returns their summation. {6Q. White a program to display the summation of two }| <htsl> {values using parameterized function. | <head> <tile> se> Functions ‘shead> < _ ‘alert(‘Summation is "+sum); = <> Output pi _2.7_JS ARRAY {0 Definition : An array isa group of elements of sam : data type. All the elements in array have inde: Syntax ‘Yar students = new Array( "Kunal", "Ishita’, "Shravi" , "Shrey")s * The array is created using new keyword. The maximum size allowed for an array is 4,294,967,295, ‘You can create array by simply assigning values as follows — var students = ["Kunal", "Ishita’, "Shreya", “Shravi”); * The index numbers are used to access the array elements ‘students[0} is the first student ~ Kunal ‘students[1] is the second student - Ishita YS. 2.7.1 Different ways to create an Array 1. Empty array without elements var empty = (): (New Syllabus wef academic year 2021-22) (96-57) (Web Scripting Languages) ‘Array with 2 string elements var days = ('Sunday", "Monday"}; 43, Array with different types of elements svar mixed = [true, 100, "Hello"}; 4. Two dimensional array with object litera sacarr = {{ls(x:l0, 20}, 2, (4:80, y:40)p), 5, The 3 element is undefined var colors = ['Red’, "Blue", indefined}; 6. No value in the 1" position, itis undefined vat hobbies = [,"Sports"]; Program 2.7.1 : Write a simple program of aray gi student name Arrays <hitle> <thead> <body> <font size=5> ‘<script language="JavaScript"> var students = new Array( "Kunal", "shita’,"Shravi", "Shrey document. write("First student is :"+students(0)); documentwrte("<hr>Second student is: "+studens ‘</script> <lfout> </body> </himl> Output T amy ¢ 3 fe7eipt.emi First student is : Kunal Second student is : Ishita Tech-Neo Publications ..A SACHIN PO. No, wan svar a, | spayig ti woo Application Development (SPPU-Sem (Web Scripting Languages) ...P: 2. Array Methods we BT Method Description ae Returns length of an array (It is property of array) concat) | Concatenates (merge) multiple arays. en If all the elements in the array satisfy the given condition of testing function, it returns ive fier) Retums array elements which satisfy the filter criteria of given function, forkach() _| Calls a specific function forall the elements in the aay. indexOf)__| Retum the index of first occurrence of given element. Returns -1 if element not found. join) Joins all the elements of an array and converts into a string lastIndexOf0 | Return the index of last occurrence of given element, It returns 1, if the specified element not found. 70) Removes and returns the last element of an array. push) ‘Adds one or more elements at the end of an array. reverse() _| Reverses the sequence of the elements of an aay. shit) Removes and returns the last element of an array. slice() Extracts a portion of an array and returns it, sort) Sorts the elements of an array spliced) ‘Adds and/or removes elements from an array. toString) __| Returns a string representation of the given array unshift) | Adds one or more elements at the beginning of an array and returns it Program 2.7.2 : Write a program to display the length of | output array and index of array element. <hinl> head> sttle> Arrays s<tile> </head> <body> <font site=5> ‘script languag Yarstudents = (°K ‘documentavrite(“Array length ; "+students.length); (ecumentwrite(’<br> First index of Kunal Program 2. ‘JavaScript"> €)0 sesiespimnt Asray length : 5 First index of Kunal : 0 Last index of Kunal : 3 % 2.7.3 Iterating Through an Array 5] Use : Iterating or traversing of an array means visting nal’, Ishita", "Shravi" , "Kunal","Shrey"]; the loops. rite a simple program of array iteration, "tatudentsindexOf(’Kunal”); oe dbeumentwrite("<br>Last index of Kunal : <title> “students JastIndesOf(°Kunal)}: Array Iteration aus <hitle> eae </head> Sito > er ta ‘<font size=5> (New Sylabus we academic year 2021-22) (P6-57) ‘each element at Jeast once. For this purpose we can use -Tech-Neo Publications ..A SACHIN SHAH Venture J tion Development (SPPU-Sem 6 ‘revi Tanguonge ver cane = [) emxlO = "Ford oar] = RM (care]2} = “Enon onda City for (var 9 = 0:4 < ems beng: 4 +) ‘ YawnSeripe document writejcars|i} + <br>") ) </script> <fhors > <Joody > <em> Program 2.7.4 : Write a program to perform various methods like adding a new element, sorting, reversing, removal of last element etc <teml> <head> <tisle> Amray Iteration ‘ Output ao neon € © feizctst nat Ford BMW Enova Honda City Feed iu Neo Publications .A SACHIN SHAH Ve Bepain how to delete an element trom array JavaScript f& Use : The delete operator is used to remove an element from an array. Deleting an element from an array doce rot affect the length property and the array becomes sparse. Also the clements which are atthe right ofthe deleted element do not get shifted to left to fill in the sap Buample sardays = (Sunday, "Monday", "Tuesday", "Wednesday"; idee daystl; 1/ delete the element “Monday” 2.7.5 Array Method : Splice() Teg” Bean” aay” “method camps invest. spliced) with” suite} splice() method Use : The splice() method is used to insert new, delete existing, and replace existing elements by new elements inthe array. + [moves the elements to higher or lower positions as perthe requirement to avoid any gap. * The first argument of splice() indicates the starting position and second argument indicates the number of clements to delete Examples varleters= [a"b','e''a" Te" dertleters splice(S. 2)); if, g (deleted elements) alenleters} Nabe.de ‘enters splice(2, 1); M/e (the deleted element) aler(leters), Madde The third argument in the splice method is used to ‘eplace one or more elements with others. varleters = "a; tletleterssplice(l, 2, "e", be (deleted snes) slenetiers), Naebed In this example, the splice stars at position 1 and Femoves two elements b and c. Then it fills the gap With the thee elements e, {and g We “W Syllabus w.e f academic year 2021-22) (P6-57) a What are JavaScript objects? List the important + builtin objects. How can you write your Own entity having its own state and behaviour (properties and methods). * For example : A flower is an object having properties like color, fragrance etc. Other examples of objects are cat, pen, bike, chair, glass, keyboard, monitor ete. * JavaScript is an object-oriented language. Everything in JavaScript is considered as an object. Examples of object ‘* Following are some of the examples of objects in JavaScript. (i) Booleans Gi) Numbers (ii) Strings (iv) Dates (¥) Regular expressions (vi) Arrays (vii) Functions * We can create our own user defined objects. in IavaSeript + JavaScript is primarily a template-based scripting language rather than a class-based language. Hence, we directly create the object without class. 284 > 1. JavaScript Object by Object Literal ‘Syntax Creating Objects in JavaScript + Following isthe syntax of creating object using object literal : object= {property :valuel ,property2:valiue2 propertyN:valueN} ‘+ As we can observe, the property and value is separated by the separator: (colon) ieee Program 2.8.1 : Write a sample program of creating object using object litera Objects <htitle> </head> Ua recn-neo Puications A SACHIN SHAH Ventre Web Application Developmen script language ="favaSerip employee = {id:101,name:" Prajakta Lonkar" salary:40000) document.wrte(employee.id +" employee salary) <script > <foa> <body> <thaml> 20-Prajakta Lonkar-40000 > 2. By creating instance of object Syntax Following is the syntax of creating instance of object : var abjectname=new Object(); Here, new keyword is used to create object. Freee Program Write a program of creating the instance of object <biml> <head> <title> Objects "+employee.name+"." Output Bom © (te | Caudle 30 hop emitangeaie, 18-Chetana Murudka-800000 By using an object constructor 4 Here, we have o create parameterized funtion, wy keyword is used (0 assign each argument yal, ccurrent object ‘©The “this” keyword refers to the current object Ue in the ite @ program using “this” keywog Objects <hitle> <shead> <body> <font size=5> ‘<script language: function student(id.sname,marks) { this.idid; this sname=sname; javaScript"> 8 = new student(20,"Gauri",90}; documentwtte(s.id+" -"“+s.sname+" «"+s.marks); </script> <Mfont> </body> </htal> Output C) dw = Gitte | creunonaeet 202hepnvnieten 20 - Gauri - 90 2.8.2 String Object * The JavaScript String object is a global object that is Used to store strings, A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all Syntax ‘Yar val = new Sting(string)s * The String parameter is a series of characters that bi been properly encoded, (New Syllabus wees academic year 2021-22) (P6-57) ye fech-Neo Publications ..A SACHIN SHAH Vent tion Development (SPPU-S; s— — (Web Scripting Languages) ..Pg. No. (2-17) 1g Methods @ stein Hes is ats of the methods availabe in Sting object slong with their description ae f Deseription toga char AQ) _| Reus the character at the apc a iol sons Joins two or more strings and returns a new string ee jee] ends With() ‘Checks whether a string ends witha specified substring. 4 15, | tromcnarCodet) | Converts Unicode valves to characters, } @ | inetudest) Checks whether a string contains the specified substring | 7,__| indexOf Returns the index of the first occurrence of the specified value in a string, al [s__[tastindexoriy Returns the index of the last occurrence ofthe specified value in a string | 9.__| localeCompare() __| Compares two strings in the current locale. j 10. _ | match) Matches a string against a regular expression, and returns an array of all matches. | Ti | repeat) Returns a new sting which contains the specified numberof copies of the original | | string. | replace() Replaces the occurrences ofa string or patter inside a string with another string, and | return a new string without modifying the original string. i search) Searches a string against a regular expression, and returns the index of the first match. | 14,_| sliced Extracts a portion of a string and returns it as a new string. 15.__| split) Splits a string into an array of substrings. [te [ startswitho Checks whether a string begins with a specified substring. [ar [subst [Extracts the part of a string between the stat index and a number of characters after it [18 | substring Extracts the part ofa string between the start and end indexes. | 19. | toLocaleLowerCas | Converts a string to lowercase letters, according to host machine's current locale. | 0) 20, | toLocaleUpperCase | Converts a string to uppercase letters, according to host machine's current locale. 0 21 | toLowerCase() _| Converts a string to lowercase letters. | 22. Ttosiring) ‘Retums a string representing the specified object. [23 Trotippercaseo Converts a string to uppercase letters. 24. | timo Removes whitespace from both ends of a string. 25. | valueori) ‘Returns the primitive value ofa String object. 32.8.3 RegExp Object ‘« Regular expressions can be defined by using following ways: RegExp object used to validate the pattern of © Using RegExp() Constructor: var characters, RegularExpression = new RegExp define methods that use regular expressions (0 RegExpt ‘flag”) Perform powerful pattern-matching and search and ‘© Using Literal: var RegularExpression = "eplace functions on text. pattern/lag; ‘ Neo Publications A SACHIN SHAH Ventu New Siabus we academic year 2021-22) (P6-57) ee cere Cu) Web Application Development (SPPU-S2U the Tern =A Suing that specifies te pater of her regular expression. regular expression oF anot © Flag ~ An optional sting containing any of ihe and“ attributes that specify global, caseinenstive and multiple matches respectively. = properties of RegExp object 1. Constructor ~ Returns the function that created the RegExp object. 2, Global - Checks whether the "g" modifier is set 3. ignoreCase - Checks whether the "i" modifier is set. (yee Senin Lana.890 bs ¢n The Math object provides a number of methods fo work with number values The Math object does not have any constructs its methods and properties are static; that is, man ‘member functions of the Math object itself, Theis way to create an instance of the Math object. Syntax var pi_val = Math. PI; yar sine_val = Math.sin(30); Properties agg "= Math Methods Following are some important methods of Math Object 4. lastindex - Specifies the index at which to start the | (yfethod Description amma ‘abs() _| Retumns the absolute value of a number. 5. multiline - Checks whether the "m" modifier is set. , eS ee a il urns the smal er greater than o 6 source - Returns the text ofthe RegExp pte Be eee | 5% Methods of RegExp object expQ_| Returns EX, where N js the argument, and E 1. exec() - Tests for a match in a string. Returns the frst is Buler's constant, the base of the natual match. logarithm. 2 fest) = Tests for a match in a string. Returns true or || floor) | Retumns the largest integer less than or equ false to anumber. 3. toString() - Returns the string value of the regular | | log) ‘Returns the natural logarithm (base E) of | expression number. 4. toSourcet) - Returns an object literal representing the || max() | Returns the largest of zero or more numbers. | specified obj Deen min) | Returns the smallest of zero or mor Following examples explain more about matching numbers characters pow( | Retums base to the exponent power, that i Expression Description base exponent. | (a-2A-Z] | Itmatches any string not containing any of | | | ™™dom() | Returns a pseudo-random number between 0 the characters ranging from a through 2 and 1, and A through Z. round() | Retums the value of a number rounded to the PP Tt matches any string containing p, nearest integer. followed by any character, in turn Talend cae t sqrt() | Retums the square root of a number. *(2IS | He matches any sting containing exact two characters. = ¥ <<b>(.*)<fo> | It matches any string enclosed within <b> td ct mip | i mches any sing conaining « followed by 20 oF more instances of te | sequence bp 2.8.4 Math Object © The Math object is used to form simple complex arithmetic operations. . ca ae (New Syllabus we academic year 2023-22) (76.57) 2.8.5 Date Object At times when user need to access the current date and time and also past and future date and times. JavaS=i Provides support for working with dates and time through the Date object. The Date object provides a system-independet stration of dates and times. * Date object can be created as vat today = new Date( Ta recneo pusicauons * SACHIN Sa ventut vp apteation Development (SPPU-Sem 6-1) pe month, hour, minute, and second, and those six omponents, as well as the day of the week, may be Guacted from a date, Dates may also be compared and converted to a readable string form. A Date is represented to a pression of one millisecond, & properties of Date object Constructor - Returns the function that created the Date object. Prototype - Add properties and methods to an object. 2 i& Methods of Date object 1. Date()- Returns today's date and time 3, getDate() - Returns the day of the month for the specified date 4, getDay0 - Returns the day of the week for the specified date 4. getFullYear() - Returns the year of the specified date § gelHlours() - Retums the hour in the specified date according to local time. 6 getMilliseconds() - Returns the milliseconds in the specified date according to local time. 1. getMinute(), getMonth(), getTime(), getTimezoneOtfset(), setDate(), setFullYear(), setHours0, setMilliseconds(), setMinutes(), setMonth0), setSeconds(), setTime() are some of the imethods used in Date object. 3 2.8.6 Number Object ‘The Number objects represents numerical date, either itegers or floating-point numbers. A Number objects are created using the number() ‘Suastictor Var num = new number(value); © Properties of Number object 1. Constructor ~ Returns the function that created the Number object. 2 Max Value - Returms maximum numerical value Possible in JavaScript. 4% Min Value - Returns minimum numerical value 4 ntl in Javascript Netative Infinity - Represent the value of negative infinity 5. Pea ¢¢_Postve ntinity - Represent the value of infinity + Add properties and methods to an object. Mew Siabus wet academic year 2021-22) (P6-S7) — Zs (Web Scripting Languages) ..Pg. No.(2-19) "Methods of Number object 1. toExponential() - Converts a number into exponential notation. 2. toFixed() - Formats a number with a specific number of digits to the right ofthe decimal toLocaleString() - Returns a string value version of the current number in a format that may vary according t0 4 browser's locale settings. 4. toPrecision() - Defines how many total digits (0 display of a number. 5. toString - Returns the string representation of the number's value. 6. valueOf() - Returns the number's value. 2.8.7 Array Object ‘+ Multpfe values are stored in a single variable using the Array object. + In JavaScript, an array can hold different types of data (ypes, which implies that an array can have a string, a ‘umber or an object in a single slot. * An Array object can be created by using following ways: Using the Array Constructor To create empty array when don't know the exact ‘number of elements to be inserted in an array var arrayname = new Array(); To create an array of given size var arrayname = new Array(size); To create an array with given elements var arrayname = new Array(“element 1”."element 2a esone”element 1°}; Using the Array Literal Notation: ‘To create empty array var arrayname =[]; To create an array when elements are given ‘ar arrayname =[“clement 1”,"element 2”,... a]: sos"element Properties of the Array object 1, Length - Retums the number of elements in the array. 2. Constructor - Retums the function that created the Array object. 3._ Prototype - Add properties and methods to an object. Te recn-neo Publications .A SACHIN SHAH Venture Web Application Development (SPPU-Sem 6-17) Methods of the Array object reverse() = Reverses the array elements cconcat() - Joins (wo or more atrays sont = Sort the elements of an array 4. push0 - Append one or more elements atthe end of an array 5. pop) - Removes and returns the last element 6. shift() - Removes and returns the first element 7 lunshift0, JoinO, indexOf), lastIndexOf0, slice(startindex, endindex) are some of the methods used in Array object. 2.9 JS EVENTS Explain’ the ‘event handling simple example. in Javascript wit Events are the actions performed by the end users while browsing the website. For example mouse move or ‘mouse click on the buttons, ‘+ When an event is fired, objects are triggered which are associated with that specific event. = The event is caught by the event handlers and in response the related code is executed, ‘= Events are basically classified in four eategories 2 Mouse events 3. Keyboard events “Form events Wie 294 Chnaton of eet > 1 window Events There are various (pe of events atcciated w window ied @)onLoad - triggered when a new page is starting up. Gi) onUnload - riggers when a page is shutting dows, il) onResize - triggers when a page is esized, Ge) omMove - triggers when a page is moved (9) omAbort - triggers when a page is cancelled (Web Scripting Languages) mnError - triggers when an error occurs. (wi) (uit onFocus - triggers when the window moves foreground. (i) onBlur + triggers when window changes 4, ‘background. > 2. Mouse Events ‘There are various types of events associated wig, G) onMousedown - triggers when Mouse Dutton is preses fon an element. Gi) omMouseup - triggers when mouse buttOM is release, Gli) onMousemove - triggers when mouse Pointer is move dnd the pointer is already over an element Gv) onMouseout - triggers When mouse pointer is move ut of an element. () onMouseover - triggers when the pointer is over a clement (9) onClick - triggers when mouse button is clicked once. (oi onDblelick = tiggers when mouse button is clicked > 3. Keyboard Events There are various types of events associated wid keyboard (@) onKeydown - Triggers when a key is pressed down. Gi) onKeyup - Triggers when a key is released li) onKeypress - Triggers when complete key sequence. down press and up release happens. > 4. Form events There are following types of events associated with form (@)onReset - triggers when the reset button on the forms clicked, a ain, ‘onSubmit - triggers when the submit button is clicks? fonSelect - triggers when a content is selected of * age. "= Using Events Al these event can be used to execute some scrip the following programs we will use mouseover * ‘mouseout events. Program 2.9.1 : Program to illustrate the use of mows | and mouseout events | ‘<himi> | ‘<body bgcolor ighegray"> (ew S/labus wat ecademic yor 200g ge fs 'ademic year 2021-22) (P6-57) Ta recto pupticaions A SACHIN HAH Ya sys gpeaon Development (SPPU-Sem 6-7) ‘blue™ | Use of mouse down and mouse up events Program 2.9.2 : Program illustrating mouse up and mouse down events <himl> <body> <i id="myidl" onmousedown="funl()" camouseup="Tun2()">Click the text! </h2> <script> funtion fun () { document getElementByld("myid1").style.color = "blue": fonction Fun20) { 1, PetmentglementBy14C‘myid tyle.clor= "backs ‘lerpt> <body> ‘hind > utput © sroeiznn x FD Ale | CrrsensAdminidestop/sample12 hem Click the text! + Write a program to show the use of events ‘ground color with DHTML. If mouse button background color should be red. If mouse button p, background color should be yellow. (> change backs ispeaes Steed shins Stet en *labus wef academic year 2021-22) (P6-S7) — (Web Scripting Languages) ...Pg. No. (2-21) function red document.body syle backgroundColor= ) function yellow() { document body style.backgroundColor=" yellow ) </script> </head> ‘<body onMouseDown="red();" onMouselip="yellow();"> </body> </himl> Output DD cunepteazeuns cin x + GO fie | Creasey Desktonlample'2 nem! Program 2.9.4: Write using JavaScript how to know which ‘mouse button was clicked, number of elements in form, and write hello world <himl> <head> <<title> Title ofthe Page Output [BY 0 roecrmerae « | © Die | coundnirOedee amg fe l= Thi page says eae _o--~ | Gia a = Tse |e a, xe Program 2.9.5 ‘mouse event. (a) If mouse left button pressed on browser it displayed message “Left Clicked”. (b) If mouse right button pressed on browser it displayed message “Right Clicked” Title ofthe Page</tile> <Jhead> <body> ‘<script language="JavaSeript"> Write JavaScript that handles following var sTestEventType="mousedown's function handleMouseEvent(e) { varevt = (¢==null ? eventse); (New Syllabus wee f academic year 2021-22) (P6-57) (Web Scripting Languages) Po. No. (2.99 var clickType = ‘LEFT: it (evuaype!=sTestBventType) return true; if (evtwhich) { if (evtwhich==3) clickType="RIGHT, : . ifielickType == LEFT) alert(‘Left button is clicked’); else iffclickType == RIGHT) alert("Right button is clicked") return trues } document.onmousedown handleMouseEvent handleMous document.onmouseup eEvent: = handleMouseE vent document.onclick </script> </body> </html> output BY 0 monn ~e © Che | catAtnnteapnge en Tepe oon Program 2.9.6 : If button named “red” is cli background should change to red and If button “green' is clicked, background should change to green <hil> <head> <title> Changing background colour <title> <script type= function red() { document body style_backgroundCol ‘text/javaseript"> } function green() document.body.stylé. background } </script> <Jhead> </head> <body> <form name=" <input type="button” yalue="Red ‘onClick="red();"><be> <br> input type= "button" value="Green" onClick= "green Dal eerie Pbizatons A SACHIN SHAH Ve agpication Development (SPPU-Sem 6-1 we Zr? oly? hun output - = o mnscor X + Fle | CAsers/Admin/Des 187: Write a JavaScript that handles following spose events. Add necessary elements, (i) JavaScript gives tbe ley code for the Key pressed. (ii) If the Key pressed is “i770, the seript should announce that vowel is esed. (ii) When the key is released background should change o ble. tonl> tead> <itle>lvaSeript

Open button" value="Close” eloseWin(:"> © fle/fess2.ntm © Mosita Firefox 2 es) Q aboutbiank = ISON stands for JavaScript Object Notation JSON is a text format which is used for storing a0 transporting data, JSON originated from JavaScript. JSON is a lightweight data-interchange format JSON is plain text written in JavaSeript object notation "self-describing” and easy to understand. JSON is easy to read and write than XML. JSON is language independent. JSON supports array, object, string, number and val¥* plea Development (SPPU m we re a The JSON structure is easily readable and 50% a lightweight and easy-f0-s6 when compared age ope dt interchange options, Following are the 1 Sages of SON: ss ervose : In contrast to XML, JSON follows a Oe espe f0 improve is users! readability. While rhing with @ complex system, JSON tends to make Jptstantialenbancements, aster : The JSON parsing process is faster than that of the XML because the DOM manipulation library in XML requires extra memory for handling large XML jes However, JSON requires less data that ultimately reals in reducing the cost and increasing the parsing geet i JSON Vs XML (Web Scripting Languages) ..Pg. No. (2-25) straightforward. Regardless of the language that you are using, you can ¢ domain objects Structured Data : In JSON, a map data structure is used, whereas XML follows a tree structure. The key~ value pairs limit the task but facilitate the predictive and easily understandable model. (4) Features of JSON 1. Simplicity 2. Openness 3. Self-Describing 4. Internationalization 5. Extensibility 6. Interoperability Both XML and JSON are widely used today. They are used as data interchange formats and both have been adopted by _pletions as a way to store structured data. The following are the differences between the JSON and XML: Sr.No. JSON XML 1.__| JSON stands for javascript object notation, | XML stands for an extensible markup language. 12 | The extension of json file is json. ‘The extension of xml file is xm [75 tte internet media type is application/json. | The internet media type is application/xml or text/xml. 4._| The type of format in JSON is data ‘The type of format in XML is a markup language. interchange. 5,__| tis extended from JavaScript Tis extended from SGML. ‘6 | lis open source means that we do not have | Tt is also open source to pay anything to use ISON. The object created in JSON has some type. _| XML data does not have any type. 4] The data types supported by JSON are ‘XML data isin a string format. strings, numbers, Booleans, null, array. 9. | Tedoes not have any capacity to display the | XML is a markup language, so it has the capacity to display data, the content. 10 [JSON has no tags. XML data is represented in tags, ie, start tag and end tag. | 11.” |SONis quicker to read and write XML file takes time to read and write because the learning \ ‘curve is higher. 12, [JSON can use arrays to represent the data. | XML does not contain the concept of arrays. | 8. Tivean be parsed by a standard javascript | XML data which is used to interchange the data, must be function. It has to be parsed before use. parsed with respective to their programming language to use KI that | | 4 Titcan be easly parsed and litle bit code is | It is difficult to parse. equired to parse the data. ~S__| File sizes smaller as compared to XML.__| File size is lager. | 6 TisON is datzoremed XML is documentorented. NX Titistess secure than XML Tis more secure than JSON. News "abs we academic year 2022-22) (P6-57) — [al rech-Neo Publications .A SACHIN SHAH Venture programming map the rntax Rules + The JSON syntax is a subset of the JavaScript syntax ‘The syntax is denved from JavaScript object notation syntax and consist of the following rules: © Data is written in name or valve pairs. © Data is separated by commas. © Curly braces hold the objects. © Square brackets hold the arrays. * The JSON format is very similar to JavaScript objects. Here, keys must be strings, written with double quotes such as {Sname”: “abe” } 5 3SON Example employees json employees": ‘(Coame’: Vivian’, "email’:'viviani@ gmail.com"), {"same":'Shraddha", "emal’:shraddham@ gmail.com"), {name":"Ronald”, "email’:"ronald|@gmail.com"} D The XML representation of above JSON example is given below ‘employees.xmi Vivian vivianl@ gmail.com Shraddhs [email protected] Ronald ronald|@ gmail.com pA_2.11 JSON DATA TYPES In JSON, values must be one of the following data types: (New Syllabus w.e academic year 2021-22) (P6-57) ee Seren Langues) F5 o Sings in JSON must be writen in double gy, Example {'name"s"Vidya") > 2. JSON Numbers Numbers in JSON must be an integer ogy g point Example {rage":22) > 3. JSON Objects ‘Values in SSON can be objects. Example { "employee": (“name’:"Prajakta", “age":30. "city":"Thane) } > 4, ISON Arrays ‘Values in JSON can be arrays. Example € “employecs":[Piyu”, "Khyati", "Inu’, "Praju’, "Sanyu', "More" } > 5. JSON Booleans ‘Values in JSON can be true/false. Example {"sale":true} > 6 JSON null ‘Values in JSON can be null. Example ‘{"middlename’:null) a eeeeanenerrnceane rere >i 2.12 JSON OB]ECT * JSON object holds key/value pair. Each Ke) © represented as a string in JSON and valve canbe of ype. 5 ‘The Keys and values are separated by colon BH" key/value pair is separated by comma. ‘The curly brace { } represents JSON object wt hrecnneo Publications A SACHIN SHAH Ve Jopment (SPP onsite ao se = ) (Web Scripting Languages) ..P9. No_(2-27, co example Tse > cine above example, employee is an object in which “salary” and "masried” are the key. In this example, ‘ote sing amber and boolean valu forthe keys, 7 Js0N object with Strings ‘pe sing value must be enclosed within double quote. Came’: "Venn, ‘email’: "vennul@ gmail.com" , iF JSON Object with Numbers {SON supports numbers in double precision floating- ist mat. The number can be digits (0-5), fractions (33, ‘dee) and exponents (¢, e+, €-,E, E+, E-) fe bat 2145, ‘ayment: 6.61789e+0 y JSON Object with Booleans JSON also supports boolean values true or false gee “ns tue, ‘woot false y JSON Nested Object Example ISON object can have another object also. Let's see a mcceme of ISON object having another object. ‘fiName": “Chetana’, ‘Nene’: "Murudkar", tee: 30, "irs; { ‘Aires: "Vira “i Mba, ‘Se Maharachta", ) PtlCode’s soorgg” ew Stabs wet academic year 2021-22) (P6-57) "JSON Array JSON array represents ordered list of values. JSON array can store multiple values. It can store string, number, boolean or object in JSON array In JSON array, values must be separated by comma. ‘The { (square bracket) represents JSON array. 5S JSON Array of Strings Let's see an example of JSON arrays storing string values {'Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Soturday"} 5 JSON Array of Numbers Let's see an example of JSON arrays storing number values, 112, 34, 56, 43, 95] "JSON Array of Booleans Let's see an example of JSON arrays storing boolean values, {true, true, false, false, trie) 5 JSON Array of Objects Let's see a simple ISON array example having 4 objects ‘Paiaployeenhy = {"name":"Chetana’, “email":"[email protected]’, “age":31}, {name":"Gauri", “emails "[email protected]", "age" ‘{name!."Prajakta, “email"[email protected]', “age":32), {"name":"Vidya", "email:"[email protected]’, "age":32} Shreedevi, "email’"[email protected]’, {"name':"Yogita’, “email":'yogin@gmailcom","age":32), {"'nanme":"Shraddha',"email":"[email protected]", “age!:32), DB 2.13 JS ARROW FUNCTIONS ‘Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way ‘compared (o regular functions. -Tech-Neo Publications ..A SACHIN SHAH Venture Web Application Development (SPPU-Sem 6-17) For example, {/ Sanction expression let x = funetion(, y) { return x * ys} Above function can be written as using an arrow function {using arow functions letx = (y) => x" ys The syntax of the arrow function is: Jel myFunetion = (argl, arg2, .argN) => { statement(s) } Here imyFunetion is the name ofthe function arg]. arg2, ..argN are the function arguments statement(s) is the function body If the body has single statement or expression, you can write arrow function as: et myFunction = (argh, arg2, ..argN) => expression Example 1: Arrow Function with No Argument If a function doesn't take any argument, then you should use empty parentheses. For example, let greet = () => console.log(' Hello); greet); / Hello Example 2: Arrow Function with One Argument If a function has only one argument, you can omit the parentheses. For example, let greet = x => console logts); sreet( Hello); / Hello Example 3 : Arrow Function as an Expression You can also dynamically create a function and use it as an expression. For example, Tet age = 5: Jet weloome = (age < 18)? () => console.log( Baby’): (0 => console.log(/Adul vweleome();// Baby Example 4 : Multiline Arrow Functions If a function body has multiple statements, you need to put them inside curly brackets (]. For example, (New Syl us wef academic year 203 (Web Scripting Languages) Tet sum = (a,b) => { let result = a + bs retum results 9, No.( } Jet result = sum(5,7); console-log(result]): // 12 5 this with Arrow Function ‘* Inside a regular function, this Keyword refers to te function where it is called. + However, this is not associated with arrow function Arrow function does not have its own this. §) whenever you call this, it refers to its parent scope. Fir example, # Inside a regular function function Person() { this.name = ‘Jack’, this.age 5, this.sayName = function () { this is accessible console.log(this.age); function innerFunc) { this refers to the global object console log\this.age); console log(this); ) innerFune(); ) } Jet x = new Person(): xsayName() Output 25 undefined Window {) EE 2.14 JS CALLBACK FUNCTIONS — In JavaScript, you can also pass a function 3 * qrzument to a function. This function that is passed & etment inside of another function is called a callb* function, For example, (SPPU-Sem 6-17) c ¢, callback) { ves + sane callck psig Sanction sete calle) | Inthe above program, a string value is passed as an argument to the greet() function, In JavaScript, you can also pass a function as an ‘ugoment to a function. This function that is passed as an argument inside of another function is called a callback function. For example, (function fandion greet(name, callback) { ‘console Jog('Hi! + '’ ++ name); - callback (); E ‘ealack fonction feoin calMe() { consledog(I am callback function’); ' ‘pesing fonction as an argument ‘pet(Peter,callMe); Output Biker en callback. function * Inthe above program, there are two functions. While ‘aling the greet() function, two arguments (a string [ute and a function) are passed. ThecallMe( function is a callback function. * te nefit of Callback Function * The benefit of w using a callback function is that you can i the result of a previous function call and then "e another function call nae Cxample, we are going to use the setTimeout() ean 0 mimic the program that takes time to ample SUH 38 data coming from the server. es —1*8tam with setTimeout() Syl 58 academic yar 2021-22) (P6-57) i (Web Scripting Languages) 1 program that shows the d function greet() { cconsole.log(‘Hello world’); function sayName(name) { console.log(Hello! + '' + name): Malling the function seiTimeout(greet, 2000); sayName(‘John’); Output Hello John Hello world AAs you know, the setTimieout() method executes 4 block of code after the specified time. * Here, the greet() function is called after 2000 nilliseconds (2 seconds). During this wait, the sayName((‘Jobn’); is executed. That is why HelloJohn is printed before Hello world. © The above code is executed asynchronously (the second function; sayName() does not wait for the first function; greet() to complete. ‘Example : Using a Callback Function In the above example, the second function does not wait for the first function to be complete. However, if you ‘want to wait for the result of the previous function call before the next statement is executed, you can use a callback function. For example, if Callback Funetion Example function greet{name, myFunction) { console.Jog(Hello world); callback fanction executed only after the greet) is executed mmyFunetion(name); } {callback function function sayName(name) { console log(Hello' + '' + name}; + // calling the function after 2 seconds sexTimeout(greet, 2000, ‘John, sayName); [el recn-Neo Publications .A SACHIN SHAH Venture * In the above program, the code is executed synchronously. The sayName() function is passed a8 a” argument to the greet) function ‘The setTimeout() method executes the greet)function ‘only after 2 seconds. However, the sayName() function ‘waits for the execution ofthe gret() function DA_2.15 JAVASCRIPT PROMISE * In JavaScript, a promise is a good way to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not. A promise may have one of three states. © Pending o Fulfilled © Rejected ‘A promise starts in a pending state. That means the process is not complete. Ifthe operation is successful, the process ends in a fulfilled state. And, if an error ‘occurs, the process ends in a rejected state For example, when you request data from the server by using a promise, it will be in a pending state. When the data arrives successfully, it will bein a fulfilled state. If an error occurs, then it will bein a rejected state. = Create a Promise '* To create @ promise object, we use the Promise() constructor, Jet promise = new Promise(function(resolve, eject){ /1do something ©The Promise() constructor takes a function as an argument. The function also accepts two functions resolve() and reject. © If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called ‘© Let's suppose that the program below is an asynchronous program. Then the program can be handled by using a promise. (web Serpting Langu29es) Na ¢p 89) : Program with a Promise const count = trues Jet countValue if (count) { : resolve("There is a count value. Felse { : reject("There is no count value”); > My new Promisefunetion (eve rey ¢ ‘eansole log(countValue): output Promise {: "There is a count value.") Inthe above program, a Promise object is cet ty takes two functions: resolve() and reject), resohey ¢ used if the process is successful and reject) is wey ‘when an error occurs inthe promise. ‘©The promise is resolved if the value of count is true, Pending a Fig. 2.18.1 : Working of JavaScript Promises JavaScript Promise Chaining Promises are useful when you have to handle more th) ‘one asynchronous task, one after another. For that, ¥¢ use promise chaining. You can perform an operation after a promise * resolved using methods then(), catch() and finally JavaScript then() method ‘The then() method is used with the callback whe # Promise is successfully fulfilled or resolved ‘The syntax of then() method is: PromiseObject.then(onFulfilled, onRejecte) (New Syllabus wes academic year 2021-22) (96-57) ——"s vert Tech-Neo Publications ..A SACHIN SHAM ya application Development (SPPU-Sem 67) jpample 2 chaining the Promise with then() eur promise ssatValve = new Promise function (resalve eject) { oelvePromise resolved) » executes when promise is resolved st -essfully countVale “shen(fanction succes console-log(result)s » Value(eesult) { thenifunction suecessValuel { ‘console log("You can call multiple functions this way."); ye ‘Output Promise resolved You can call multiple functions this way. 4 In the above program, the then() method is used to chain the functions to the promise. The then() method is called when the promise is resolved successfully. + You can chain multiple then() methods with the promise "© JavaScript catch() method ‘+The catch() method is used with the callback when the promise is rejected or if an error occurs. For example, //retams a promise let countValue = new Promise(function (resolve, reject) { teject(Promise rejected’); ys [executes when promise is resolved successfully oantValuethen( function successValue(result) { console logicesult); executes i there is an error eateh( function errorValue(eesult) { ‘console-log(result); (ew Syllabus wef academic year 2021-22) (P6-57) (Web Ser Output Promise rejected is rejected. And the catch() method is used with a promise to handle the error © Inthe above program, the promise Pending oe a5 < RoninF rer) Roun > ecm) Fig. 215.2 © Working of JavaScript promise chaining JavaScript Promise Versus Callback ‘© Promises are similar to callback functions in a sense that they both can be used to handle asynchronous tasks. ‘© IavaScript callback functions can also be used to perform synchronous tasks. © Their differences can be summarized in the following points: © JavaScript Promise © The syntax is user-friendly and easy to read. © Error handling is easier to manage. Example pi0.then(funetion(result) ( return api2Q ; Pithen(function(result2) { retum api3)s Pithen fimetion(result3) { 1! do work }scatch(funetion(error) { ‘handle any error that may occur before this point de 52° JavaScript Callback ©The syntax is difficult to understand. ‘© Error handling may be hard to manage, Example ‘api(function result){ api2(function(result2){ Tech-Neo Publications ..A SACHIN SHAH Venture Web Application Development (SPPU-Sem 6.17) ‘api8ifunction( result }{ do work iMieeror { do something o something © JavaScript finally() method * You can also use the finally() method with promises. ‘The finally() method gets executed when the promise is either resolved successfully or rejected. For example, returns a promise let coun: Value = new Promise(function (resolve, reject) { could be reslved or rejected resolve/Promise resolved’ bs add other blocks of code ccourtValue finally( fanction greet() { console.log(This code is executed’) This code is executed. © JavaScript Promise Methods There are various methods available to the Promise object Method Description ‘aliiterable) | Waits for all promises to be | resolved or anyone to be rejected allSettiediiterable) | Waits until all promises are either resolved or rejected Vanylterable) | Retums the promise value as soon | as any one of the promises is | fulfilled [Tracetiuerable) | Wait until any of the promises is | resolved or rejected [ rejectreason) | Retums a new Promise object that | is rejected forthe given reason [resolve(value) | Returns a new Promise object that ngUag0) Pg. Ne (Wob Scripting L Trreolved with the piven vag Lani Ack MO had fama Md a nally) “Appends a handler to the promary Wh 16 Js ASYNC-AWAIT FUNCTIONS —~ FEASNCAWATT FUNCTIONS — 4 We use the async keyword with a function to represen that the function is an asynchronous function ty, syne function returns a promise ‘The syntax of async function is 1, parameter2, ..paramater§) syne function name(parame' { J] statements } Here, © name - name of the function ‘+ parameters - parameters that are passed tothe function Example of asyne Function //asyne function example asyne function f() { console log(Asyne function.) return Promise.resolve(1); } 105 Output Asyne function. + Inthe above program, the async keyword is used the function to represent that the function asynchronous. * Since this function returns a promise, you can Use chaining method then() like this ‘async function {0 ( ceonsole.log('Asyne function.); relum Promise.resolve(1); } {O.then(function(result) { console log(esult) Ms (New Syllabus we academic year 2021-22) (P6-57) hrecrneo Publications ..A SACHIN SHAH Vert™® agpetion evelopment (SPPU-Sem 6-1) output sere Be tthe above program, the {function is re solved and the then() method gets executed, : 7 savaScript await Keyword ‘he await keyword is used inside the as wait forthe asynchronous operation, ‘The syntax 0 Use await i: areal = avait promise: Te use of await pauses the asyne function until the promise retums a result (resolve or reject) value, Fog example, we ee = new Promise(function (resolve, edfineout(fanction Q) { sesolve(Promise resolved’)}, 4000); ye function to reject) { {ane fonction sxe retin asyneFune() { vait until the promise resolves letreslt = await promise; console dog(eesult); ‘omolelog(hell!); } calling the asyne function, ‘nunc tpt mise resolved tte * Tee above program, a Promise abject is created and it S resolved after 4000 milliseconds. Here, the ScFunc() function is written using the async fetion Be vai keyword waits for the promise to be lee (resolve ot reject). AS wit promis; avai tH? i displayed only after promise value is the result variable, : 6 Soyer, Program, if await is not used, hello i (Web Scripting Languages) ..Pg. No. (2-33) me mace ne, ee + ris toe ea ey, ty on om cot et tee cin Fig. 2.16.1 "Working of async/await function * The asyne function allows the asynchronous method to bbe executed in a seemingly synchronous way. Though the operation is asynchronous, it seems that the ‘operation is executed in synchronous manner. ‘This can be useful if there are multiple promises in the rogram. For example, let promisel; let promise2s let promises; syne function asyneFune() ( Jet result = await prot sel; let result2 = await promise2; let result3 await promise3; console.log(result}s console.log( result); console.log(result); + * In the above program, await waits for each promise to be complete. © Error Handling ‘+ While using the async function, you write the code in a synchronous manner. And you can also use the catch) method to catch the error. For example, asyncFunc().catch( catch exer and do something ) # The other way you can handle an error is by using try/catch block. For example, If apromise Feo ete eatin fore Promise resolved, ey a wef academic yer 2021-22) P6-57) seiTieout function 0 { eeaeassaee (Web Scripting Languages) e Web Appioation Development m6.) 2.No ton Dovelopment (SPPU-Sem 6 SIT ised vpn ofc sense resolve( Promise resolved')}, 4000) ‘CU oF tap ys async function fazyne function asyneFune) ( wail until the promise resolves Jet reeult = await promise; console logiresult) catch(error) { console log(erroel: , } calling the asyne function asyncFunc(); // Promise resolved * In the above program, we have used try/eatch block t0 handle the errors. If the program runs successfully, it will goto the try block. And if the program throws an error, it will goto the catch block. Benefits of Using async Function ‘The code is more readable than using a callback or a promise Error handling is simpler. Debugging is easier. »»_2.17_JS ERROR HANDLING © JavaScript is a loosely-typed language. It does not give compile-time errors. So sometimes, you will get a runtime error for accessing an undefined variable or calling undefined function etc. ‘© JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#, Syntax ty { W/ code that may throw an error I ‘eatch(ex) 1 I code to be executed if an error oceurs + finally( (New Syllabus wef academic year 2021-22) (P6-57) ) try: wrap suspicious code that m, ay throw an try block fn catch: write code to do something in catch atch bl that will give you error information, Generate mig block is used t0 log an error or digi? messages to the user. i + finally: code in the finally block wit ayy executed regardless of the occurrence of an finally block can be used to complete the task or reset variables that might have chan ‘error occurred in try block. Example of Error Handling in JS ror, ering Bed been ty { varresult = Sum(10, 2 , eatch(ex) { document.getElementByld(‘errorMessage’).innerHTML = t output ‘Sum is not defined yet Demo: Error Handling RefereaceEror: Sum is not defined * In the above example, we are calling function Which is not defined yet. So, ry block will ‘error which will be handled by catch block. Ex inl ‘error message that can be displayed. * The finally block executes regardless of wl happens. Example of finally Block & { ae = Sumo, 20 catehiex) ( document. getElementByld(errorMessase" ‘Sum is not defined yet innerHtTML = ot Tad recn-neo Putcaons .A SACHIN SHAY web Application Development (SPPU-Som 6-1T) } finally = idocument.getElementByld("message"), inner HTML = saa block executed"; ) ‘Output Demo: Error Handling ‘Error: RefereneeEtror: Sum is not defined finally block executed «throw : Use throw keyword to raise a custom error. Example of throw Error y { throw "Error occurred’: } catch(ex) { alert{ex): } Output Demo: throw Error occurred © You can use JavaScript object for more information about an error. Example of throw error with error info iy ( throw { ‘number: 101, message: "Error occurred" k } catch (x) { i alert(ex.number + "=" + ex.message)s (New Syllabus we f academic year 2021-22) (P6-57) (Web Scripting Languages) ...P9. No. (2-35) Output: Demo: throw 101- Error occurred Dy 2.18 AJAX © AJAX is an acronym for Asynchronous JavaScript and XML. + Itis nota programming language. Its a technology for developing better, faster and interactive web applications using HTML, CSS, JavaScript and XML. © HTML : Hypertext Markup Language (HTML) is uused for defining the structure of a web application. © CSS + Cascading Style Sheet (CSS) is used to provide look and style to a web application, © JavaScript : JavaScript is used for making a web application interactive, interesting and user friendly. © XML : Extensible Markup Language (XML) is a format to store and transport data from the web server. © It is a group of inter-related technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest ete. * AJAX allows you to send and receive data asynchronously without reloading the web page. ‘* AJAX allows you to send only important information to the server not the entire page. So only valuable data from the client side is routed to the server side. It ‘makes your application interactive and faster. % 2.18.1 Asynchronous in AJAX + Asynchronous means that the web application could send and receive data from the web server without refreshing the page. + This background process of sending and receiving data from the server along with updating different sections of a web page defines Asynchronous property/feature of AJAX. Tech-Neo Publications ..A SACHIN SHAH Venture Web Application Development (SPPU-Sem 67) 2.18.2 Benefits of Ajax 1. Using AJAX you can create better, faster, and more user-friendly web applications. ‘Ajax is based on JavaScript, CSS, HT etc. So, you can easly lear. 3, Ajax behaviour and works is like a desktop application. So, Ajax use for creating a rich web application. Working of AJAX It creates more interactive techniques for faster and more efficient web applications by using JavaScript, XML, CSS, and HTML. For various web applications, Ajax uses various techniques like : * In Ajax, when the user needs to create content, XHTML is used while CSS is used for presenting the user request purpose, the document object model (DOM) and javascript both will be used to display the content dynamically. ‘© By using synchronous methods in web applications, can be transmitted and received effectively, for example, when you fill a form and submit it. You will be automatically directed tothe new server with that page information. After hitting the submit button in the background, javascript sends a request, and with the response generated, it will update to the current sereen. In this process, the user will be unaware of the background XML code requests. + XML is used as a format to generate and receive the server data in any format. © While most of the web browsers are dependent on web server technology, it is independent of web server ML and XML 218.3 information software. Pata Prowse HTTPRagoe crate a atte Cro maces an Roque aoe ‘ers caateao = Sana HteRecust o— Fig. 218.1 : AJAX Working = Below mentioned are the places where Ajax is used (Web Seripting Languages) Where to use AJAX? Login forms : Eg: user can type their login credential in the original page form, their software will seng 7 request to the server to logged in, and the page wit je updated as needed. ‘Auto-complete : When you run a query in the Googie search engine with the help of auto fill settings suggestions will be shown in drop down below. Rating and Voting : The voting can decide the site's main content in web pages like Digg and Reddit by bookmarking them. . Updating with user content : When a user posts 2 tweet, it will be added to their feed, and everything is updated. Now it is used by tweeter to run their trending topics page © Form submission and validation, © It makes web applications quicker, and the numbers of responses are also reduced. © Light-boxes are used nowadays instead of pop vps. © Using Ajax with flash application Examples of Ajax Application Given below are the lists of web applications that ‘commonly use Ajax a @ @) Geeele Suzgests that auto-complete options will be hile typing when a user enters the search By Goon oss Search engine. Suggestions given ss = be navigated by using operational keys. experiences mane penne hile operating, and user mn. This Map uses Ajax to drag the wi willbe ean ee HSE Without using Butons ta Google maps are This is a real-time ‘manipulate the data directly works on pee Change the view settings. Ajax installations. Firstly, wep browser without any plugin used Ajax, but duc Microsoft internet explorer spolications lke chrome, yoy, Ctsbilty, more web ill... ete. using this (New Syllabus w.e f academic year 2021-22) (6-57) Tech-Neo Publi Matos ok SACHIN SHAN Venture Web Application Development (SPPU-Sem 6-17) Advantages and Disadvantages of Ajax & advantages of Ajax 2 Reduces the server traffic and increases the speed Iris responsive, and the time taken is also less Form validation Bandwidth usage can be reduced ‘Asynchronous calls can be made; this reduces the time for data arrival a Disadvantages of Ajax 1. Open-source ActiveX request is created only in internet explorer and anewly created web browser. For security reason, you can only access information from the web host that serves pages. Fetching information from other servers is not possible with Aix. 2.19 AJAX DESIGN BASICS * AJAX uses the XMLHttpRequest object to ‘communicate with the server. The Fig. 4.2.1 shows the flow of AIAX. ‘An important role is played by the XMLH«pRequest ‘object in AJAX processing. Request is sent by the user through UI (User interface) and a JavaScript call goes to XMLHttpRequest object. Using the XMLHttpRequest object, the HTTP Request sent tothe server. Now the server interacts with the database using any of the server side scripting language like JSP, PHP, Servlet, or ASP.net. Pg. No. ( Data is retrieved from the database ax per the equirement. Server sends the data in the form of XML. or JSON through the XMLHttpRequest callback funetion, * Then the data is displayed using HTML and C35 on the browser, ing Languages) 2.19.1 AJAX Processing Steps and Ajax Script Steps to process AJAX > Step 1: An event by the clients fired. ‘When an event is fired, a JavaScript method gets called. Example validateID() JavaScript method is mapped as an event handler to an onKeyPress event on input form field. The id here is "myid" ‘, > Step 2: An XMLHttpRequest object is created var ajaxReqObj: function ajaxFungT > THis variable makes AJAX yf sjaxReqObj = new XMLHupRequest(); cng Ufone. rts Sas] c wy ajaxReqObj = new activeXObject("Msxml2.XMLHTTP"); Web server |] *MuHtoRequest Business Logic Implementation | (PHP, serdatete) } uf Internet Explorer cath (e) { by ajaxReqObj = new ActiveX Object(’Micrasoft.XMLHTTP"); Feateh (&){ 1 Exception occurs alert("Your browser broke!"); return false: d d (New Syllabus w.e academic year 2021-22) (P6-57) [ed rec-teo Publiations -A SACHIN SHAH Venture tion Devolopment (SPPU-Sem 6-1T). > Step 3: The XMLHupRequest object is configured In this step, we will write a function that will be triggered by the client event and a callback function processReqFun() will be registered. faction validatetD( { ajanFun(: cegh ajexReqObj.onreadystatechange processReqFun() is callback if Charger) target = document geiElementByld( myid'); var url = "validatefid=" + escape(targt.value): ajaxReqObj.open('GET, uth, true); ajaxReqObj.serdiaull); > Step4 :An asynchronous request is made by the XMLHupRequest to the Webserver. * Here we will make request to webserver. This request can be made using XMLHttpRequest object ajaxRequest. fanction validateID() { ajexFun(): jaxReqObj.onreadystatechange = processReqfun; if Charget) target = document getBlemeniByldCmyid), var url = "validateZid=" + escape(targt.value}: sjesReqQbj.opentGET", ur, trwe)s 5 BerBesObend a Internet Explorer © Now consider in the textfield, Subhash as userid, then in the request, the url will be "validate?id=Subhash", processReqFun() is callback function > Step 5: The Webserver returns the result in XML. format. + The server side script can be implemented in any server side language using the following logic, * Accept request from the client side. Parse the input given by the client. + Bxecute necessary processing. # Send the output tothe client in response. © We will use the Servlet for this purpose. HpserletResponse response) throws LOE epg, ServletException { String 1D = request.getParameter('d"); if (AD I= mull 88 accounts contarnaKey 1D iin, { reaponse.setContentType("text/xral”); response.setHleader("Cache Control, "no cache"), response getWriter()-write(‘true"}; } { response setContentType(‘text/xm!") response.setHleader("Cache Contr response.getWriter().write(alse"); } : ' "no cache”) > Step 6 : The callback() function is called by the XMLHupRequest object and processes the result. * When the state of XMLHinpRequest object is changed to the readyState, then the XMLHttpRequest objec ‘was configured to invoke (call) the processReqFun) method. * The result returned by the server is received by this function and required processing will be done. Now see in the given example, this function will set message ‘depending upon the webserver's returned value functionprocessReqFun() iffreq.readyStat ( iffreg.statu { > Step 7 : The HTML DOM is update. * Now this is the last step. Here the HTML documes Will be updated. Process will be as follows * UsingDOMAPI, the JavaScript receives a reference 10 ‘ny element in the web page (New Syllabus wee academic year 2021-22) (P6-57) Ul ecto Puctns a SACHIN SHAH Verte wen Application Development (SPPU.Som ent getElement Byld("aserldMag sj verleg "i the TD attibute ofan element present in the FATML document Using JavaScript, the attributes of clement ean be imoified. The style properties can be modified or child elements can be added, modified or removed eripttype="tewtjavaccript"> a fietionse’MsgDOM (mse) saroserMeseageElement= document getElementByld("userLdM varmsgTexts it 7) uerMessageElement.style.color="red', smgfext="Wrong Userld"; } else 4 sedfeeageElement.style.color="green's magText="ValidUserld", } sarmsgBody= document.createTextNode(msgText); ifwserMessegeElement.childNodes{O)) { userMessageBlement.replaceChild(msgBody userMessageE If the messageBody element is already created then just replace it otherwise append the new element sent.childNodes{0)); x } che { ‘user MessageElement.appendChiid(msgBody); } } & Shrip> ‘Sbodybgcolor="gray”> = "userldMsg">
“Ibody> ere » 2.20 CALL HTTP METHODS USING AJAX * Tomake an HTTP call in Ajax, you need to initialize a Rew XMLHttpRequest() method, specify the URL endpoint and HTTP method (in this case GET), (New Syabus w.ef academic year 2021-22) (P6-57) (Web Scripting Languages) ...Pg. No. (2-39) ‘* Finally, we use the open() method to tie the HTTP method and URL endpoint together and cal the send) method to fire off the request. We log the HTTP response to the console by using the XMLHTTPRequestonreadystatechange property Which contains the event handler to be called when the readystatechanged event is fired EP AJAX Request © AJAX sends a request to a server by using open) and send() methods of the XMLHttpRequest object. Following code snippet illustrates how an AJAX Fequest can be sent to the server. -xhttp.open(*GET’,"ajax_info.txt true); http send); ‘+ Inthe above code snippet, the GET is the request type, ‘ajax _info is the location of the server type and true shows that the request is asynchronous, ‘* Following are the methods used to send a request in AJAX. open(method, url, async): Specifies the type of request ‘© method: the type of request: GET or POST © url the server (file) location ‘© async: true (asynchronous) or false (synchronous) 2. send() sSends the request tothe server (used for GET) 3. sendi(string) : Sends the request to the server (used for POST) © AJAX Response © The readyState property holds the status of the XMLHttpRequest. © The onreadystatechange property defines a function to be executed when the readyState changes as shown in the following code snippet. var xhttp = new XMLHupRequest(); xhtip.onreadystatechange = function() { if this xeadyState == 4 && this.status == 200) { document.getElementByld(‘demo")innes HTML = this.esponseText; «In the above code snippet, the response is decided by two properties of XMLHttpRequest: readyState and status, When the status is 200 and readyState is 4, the response is ready. © The status property and the statusText property holds the status of the XMLHttpRequest object. [i ere ubiatons.A SACHIN SHAR Venture Wob Application Development (SPPU-Sem 6-IT) (Web Scripting Languages) Request Object Methods ee 1 XMLHttpReq ods Description J careadystatechange | Defines a function to be called a mest) | Crates anew when adyState property ww XMLHttpReques! om aan nm XMLHttpRequest object readyState Holds the status ofthe abort) Cancels the current reques XMLHupRequest {etAlIResponseHeaders() | Returns header 0: request no initialized information 1: server connection established GaiResponseHeader) Retwms specific head 2: request received information 3: processing request ‘open(method, url, asyne, | Specifies the request] 4 request finished and response is ||| Pere method: the request type | ready GET or POST | status 200; "OK" url: the file location | 3: "Forbidden" asyne: true (asynchronous) 404: "Page not found” or false (synchronous) | statusText Returns the status-text (e.g. "OK" user: optional user name | or "Not Found”) sw: optional password "Server Response Properties send) eh OES There are two server response properties, which are as Used for GET requests ee send(string) Sends the request 10 the 1, _responseText : Returns the response from the server as server. a JavaScript string, setRequestHeader() ‘Adds a labeW/Value pair to 2 responseXML: Returns the response from the server the header to be sent as an XML DOM object. "5 Server response Methods ‘There are two server response methods, which are as follows: 1. getResponseHeader() : Returns information from the server resource. 2. getAllResponseHeaders() : Returns all the header information from the server resource. ‘The AJX request and response functions can be used with XMLHttpRequest API. "© XMLHttpRequest API ‘+ AJAX comprises important API as XMLHttpRequest, which transfers XML data using HTTP to and from the web server. XMLHttpRequest is an API, which was initially built by Microsoft. It is used by various scripting languages such as JavaScript, VBScript, etc. + The XMLHtpRequest object is used to exchange data with a web server in the background. This means that it is possible to update parts of a web page, without reloading the whole page specific header Program 2.20.1 : Create AJAX Application Create a simple XMLHttpRequest, and retrieve data from a txt file. "Create a file Ajax.html ‘

The XMLHupRequest Object

jQuery ‘

Example of jQuery Selector

'Try it

Output in.je"> © essissa/pi.nom jQuery Bxample of jQuery Selector Ty (cert Ride the paragraph) > — @) The fid Selector The jQuery Md selector selects the HTML id attribute of the HTML tag to find the specific element. All the elements should have unique id. To search an element with a given id, hash character is written which is followed by the HTML element id Ss(’#idl") nn Program 2.22.3 : Write a program to demonstrate the use of Web Seripting Languag%®) P5 Ne (g 4) script sro="jquery-3.2.1.min,js"> jQuery

Example of jQuery selector

Try it

< Output ‘ata/oten! € © tesraseypt net iQuery ci Tyt (Getere | > (©) The class Selector ‘The jQuery class selector finds elements with a specific class. To search an element with a specific class, period character is written which is followed by the name of the class, $(".myclass") a Program 2.22.4: Write a program to demonstrate th class Selector. ‘ ‘Steript sre="jquery-3.2.1.min,js"> ‘$(document).ready(function(){ Hid Selector. $Cburtee’y sclick(function(){ % .myclase”)hide(); (New Syllabus w.ef academic year 2021-22) (P6-57) Tabrech-neo Publications ..A SACHIN SHAH > seeps” >jQuery = 'myclass"> Example of jQuery selector

Seen Click Here<[button> iby chon! 3235 DOM MANIPULATION WITH QUERY 3 2.23.1 Changing Styles jQuery css() Method is used to set or retum one ot mre style properties for the selected elements. (Web Scripting Languages) ..P9.No_ (2-45) Ye

Phoenix InTech 1kground-color:red"> Paragraph 1.

ackground-colorigreen’> Paragraph 2.

ckground-color:blue"> Paragraph 3.

Paragraph 4.

Phoenix InfoTech YS. 2.23.2 Creating and Appending Elements ‘GQ. “White an example (program) to create and append {_H1MLelementin jQuery JQuery provides append() method to add an element. Program 2.23.2 : Write a program to create and append Soins To set a specified CSS property, use the following | HTML element in jQuery. ju: ‘ «ss propertynaine, Value"); Sm Example Siar ‘§(p'}css("background-color”, "skyblue"); ‘sre="bitps://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery. amine" Program 223.1 : Write a program to change style in eer. $(document) ready function) { eee $(-#btA) click (function 8(’p").append(" This is New Appended = text.")s a Yi: SSlbpejaxgoogleaps. com/ajaxMibs/jquery/3.2.Uiquery- | §(#b1nB").click(function(){ Binb!> ‘$('ol”) append(*<1i>Nagpur"); in, »: Mecsmen) ready (function) { »: ‘$buton) ck function) { jh Petbuckground-colr,skyblve); pn 7 Q New Ssabuew.et academic year 2021-22) P6-57) — [Bb rech.neo pulications A SACHIN SHAH Venture

You might also like