0% found this document useful (0 votes)
6 views

Unit-2 - Java Script_xml

The document is a comprehensive guide on JavaScript, covering its introduction, syntax, variables, data types, operators, and event handling. It also discusses the use of JavaScript in web development, including client-side and server-side applications, as well as mobile app development and machine learning. Additionally, it provides examples of JavaScript code and explanations of various concepts such as functions, arrays, and the Document Object Model.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit-2 - Java Script_xml

The document is a comprehensive guide on JavaScript, covering its introduction, syntax, variables, data types, operators, and event handling. It also discusses the use of JavaScript in web development, including client-side and server-side applications, as well as mobile app development and machine learning. Additionally, it provides examples of JavaScript code and explanations of various concepts such as functions, arrays, and the Document Object Model.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 171

Vallurupalli Nageswara Rao Vignana Jyothi Institute of

Engineering &Technology

Department of Computer Science & Engineering

SUBJECT: Web Technologies


Subject Code:
2024-25

Topic Name: JAVA SCRIPT


III year-IIsem, sec- B:

Dr. M.Gangappa
Associate Professor
Email: gangappa_m@vnrvjiet

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 1
Client-side Scripting: Introduction to JavaScript, JavaScript language –
declaring variables, scope of variables, Operators, Conditional Statements,
JavaScript Loops, Functions, Array, Array functions, String object, Date
object, Regular expression object, Event handlers (Keyboard Events,
Mouse events, Form Events, Window events), Document Object Model

XML: Introduction, Tree, syntax, Elements, Attributes, Namespaces,


Display, HttpRequest, DOM, DTD, Schema Form validation., Dynamic HTML
with Java Script, Ajax

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 2
Agenda
1. JavaScript 10. Event and Event handling in Java script
2. JavaScript Comment 11. Pop – up boxes in Java script
3. JavaScript Variable 12. Form validation in Java script
4. JavaScript Data Types 13. Java script InnerHTML
5. Primitive data types 14. DHTML
6. Conditional statements
7. JavaScript Functions
8. JavaScript object
9. Implicit objects
1. JavaScript array
2. Math object
3. String Object
4. Regular Expression Object
5. Date object
6. Number Object
7. Window object
8. Document object

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 3
❑ JavaScript is a light weight, interpreted and dynamic programming
language.
❑ It allows client-side script to interact with the user and make the
dynamic pages.
❑ JavaScript can be implemented with JavaScript statements that
are placed within the <script>…</script> HTML tags in a web page
❑ It is a case-sensitive language.
❑ JavaScript is supportable in several operating systems including,
Windows, macOS, etc.
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 4
Java script was started in the year 1995 to fulfil the dynamic nature of web pages for the client side applications.
Now JS has been widely using in different variations.
1) Client side web development
JavaScript
JQUERY --- library/API
Angular JS
React JS etc.
2) Server side Web development
Node Js is the library of Javascript
Express JS
3) Mobile APP
4) Browser plugins/patches/Extensions
5) Machine Learning
TensorFlow JS

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 5
JavaScript provides 3 places to put the JavaScript code:
➢ within body tag
➢ within head tag
➢ external JavaScript file.
code between the body tag
<html>
<body>
<script type="text/javascript">
alert("Hello Javat-point");
</script>
</body>
</html>
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 6
code between the head tag

<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 7
External JavaScript file
➢ It provides code re-usability because single JavaScript file can be
used in several html pages.
➢ An external JavaScript file must be saved by .js extension.
➢ It increases the speed of the webpage.
index.html
message.js <html>
<head>
function msg(){ <script type="text/javascript" src="message.js"></script>
alert("Hello VNR VJIET");
} </head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 8
JavaScript Comment

There are two types of comments in JavaScript.


1.Single-line Comment
2.Multi-line Comment

1.<script> 1.<script>
2.// It is single line comment 2./* It is multi line comment.
3.document.write("hello javascript"); 3.It will not be displayed */
4.</script> 4.document.write("example of javascript multiline
comment");
5.</script>

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 9
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are
two types of variables in JavaScript :
➢ local variable .
➢ global variable.
Correct JavaScript variables JavaScript local variable
1.var x = 10; A JavaScript local variable is declared
2.var _value=“CSE"; inside block or function.
<script>
function abc(){
let x=10;//local variable
}
</script>

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 10
Variable declaration in java script
Parameters Var Let

Introduction in JavaScript Var has been a part of Let was introduced in the
JavaScript since its ES 2015 (ES6) version of
inception. JavaScript.
Scope Var is globally scoped. Let is block-scoped.

Access and Declaration Var can be declared and Let can be declared
accessed globally. globally, but its access is
limited to the block in
which it is declared.
Redeclaration Variables declared using Variables declared with let
var can be re-declared and can be updated but not re-
updated within the same declared within the same
scope. scope.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 11
JavaScript global variable
A JavaScript global variable is accessible from any function.
<html>
<body>
<script>
var data=200; //global variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();
//calling JavaScript function
b();
</script>
</body>
</html>
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 12
JavaScript Data Types
JavaScript provides different data types to hold different types
of values. There are two types of data types in JavaScript.
1.Primitive data type
2.Non-primitive (reference) data type
JavaScript is a dynamic type language, means we don't
need to specify type of the variable because it is dynamically
used by JavaScript engine.

1.var a=40; //holding number


2.var b= "Ram"; //holding string

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 13
Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value


Null represents null i.e. no value at all

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 14
JavaScript Data Types

JavaScript - String
String is a primitive data type in JavaScript. It must be enclosed in single
or double quotation marks.

Example: A string can also be treated like zero


"Hello World" index based character array.
'Hello World'
var str = 'Hello World’;
str[0] // H str[3] // l
str[1] // e str[4] // o
str[2] // l
str.length // 11
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 15
JavaScript - String
String can be accessed using for loop.

<p id="p1"> </p>

<script>
var str = 'Hello World';

for(var i =0; i< str.length;i++)

document.getElementById("p1").innerHTML =
document.getElementById("p1").innerHTML + str[i];
</script>

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 16
String-Concatenation
String can be concatenated using plus (+) operator in JavaScript.

var str = 'Hello ' + "World "

Include quotation marks inside string


Escape characters in JavaScript help inserting special characters in the
webpage without breaking the code. We use the backslash (\) character
to specify a special character.
Notation Meaning
\’ It adds a single quote in the page.
\” It adds a double quote in the page.
\n (Newline) It takes control to the next line on the page.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 17
String- quotes

JavaScript - Number
The Number type represents both integer and floating-point numbers
and has 3 symbolic values:
❑ +Infinity
❑ -Infinity
❑ NaN (Not-a-Number)

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 18
Boolean

The Boolean type represents a logical value that has two possible
values: true and false.

Null
The Null datatype in JavaScript only represents null
value ( non-existent or invalid object or address )

❑ It means we have defined a variable but have


not assigned any value yet, so value is absence.
❑ A null value evaluates to false in conditional
expression.
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 19
undefined
Undefined is also a primitive value in JavaScript. A variable or an object has an undefined value
when no value is assigned before using it.

An undefined evaluates to false when used in


conditional expression.

Normally, we use undefined for checks like seeing if a


variable has a value assigned.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 20
Operators are used to assign values, compare values, perform arithmetic operations, and
more.

There are different types of JavaScript operators:

❑ Arithmetic Operators
❑ Assignment Operators
❑ Comparison Operators
❑ Logical Operators
❑ Conditional Operators
❑ Type Operators

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 21
Arithmetic Operators
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 22
Comparison Operators
Operator Description Example
== Is equal to 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 23
Assignment Operators

Operator Description Example


= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a =
200
/= Divide and assign var a=10; a/=2; Now a = 5

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 24
Logical Operators

Operator Description Example


&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 25
typeof operator

The type of a variable is determined by the type of the value assigned to it. JavaScript has
a special operator called typeof which lets you get the type of any value.

The typeof operator takes only one operand . It evaluates the type of the operand and
returns the result as a string.

Syntax:

typeof(operand) typeof(typeof 007); // returns 'string'


Example:
typeof 007; // returns 'number'

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 26
Typeof operator and its result

typeof 0; //'number'

typeof +0; //'number'

typeof Infinity; //'number'

typeof NaN; //'number'

typeof Number('100'); //'number'

typeof Number(‘VNR VJIET'); //'number'


typeof '100'; //'string'

typeof String(100); //'string'

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 27
Examples
let x = 5 + 5;

let y = "5" + 5;

let z = "Hello" + 5;

Adding two numbers, will return the sum, but adding a number and a string will
return a string:

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 28
JavaScript supports the following forms of if..else statement −
❑ if statement
❑ if...else statement
❑ if...else if... statement.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 29
check if the number is positive.
if(expression){
//content to be evaluated let number = parseInt(prompt("Enter a number: "));

} // check if number is greater than 0


if (number > 0) {
// the body of the if statement
console.log("The number is positive");
}

console.log("The if statement is easy");

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 30
if (condition) {
// block of code if condition is true
} else { check if the number is positive.
// block of code if condition is false
}
let number = parseInt(prompt("Enter a number: "));

// check if number is greater than 0


if (number > 0) {
// the body of the if statement
console.log("The number is positive");
} else {
console.log("The if statement is easy");}

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 31
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 32
check if the number if positive, negative or zero
const number = prompt("Enter a number: ");
// check if number is greater than 0
if (number > 0) {
console.log("The number is positive");
}
// check if number is 0
else if (number == 0) {
console.log("The number is 0");
}
// if number is neither greater than 0, nor zero
else {
console.log("The number is negative");
}

console.log("The if...else if...else statement is easy");

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 33
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-
in loops.

There are four types of loops in JavaScript.


1.for loop
2.while loop
3.do-while loop
4.for-in loop

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 34
The syntax of for loop in JavaScript is as follows −

for (initialization; test condition; iteration statement) {


Statement(s) to be executed if test condition is true
}
Print the numbers from 1 to 5 The JavaScript for loop iterates the elements
<script> for the fixed number of times.
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 35
while (condition)
The JavaScript while loop iterates the elements for the
{
code to be executed infinite number of times. It should be used if number of
}
iterations is not known.

<script>
var i=11;
do{ while (i<=15)
code to be executed {
document.write(i + "<br/>");
}while (condition); i++;
}
</script>
Write JS program to find the sum of positive numbers if the user enters negative
number, the loop terminates.
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 36
The JavaScript for-in loop is used to cycle through an object's properties.
const salaries= {
Jack : 24000,
Paul : 34000,
}
Jack : $24000,
// using for...in
Paul : $34000,
for ( let i in salaries) {

// add a currency symbol


let salary = "$" + salaries[i];

// display the values


console.log(`${i} : ${salary}`);
}

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 37
Write a JavaScript program to:

1. Calculate the Area of a Triangle


2. Swap Two Variables.
3. Solve Quadratic Equation.
4. Find the Largest Among Three Numbers.
5. Print All Prime Numbers in an Interval.
6. Find the Factorial of a Number.
7. Display the Multiplication Table.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 38
A JavaScript function is a block of code designed to perform a particular task.

JavaScript functions are defined with the function keyword.

function functionName(parameters) {
// code to be executed
}

Code reusability is advantage of functions.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 39
JavaScript object
❑ Any real world entity is called an object. Example: Table is an object.
❑ the primitive data-types all store a single value each (depending on their
types).
❑ Object is a non-primitive data type in JavaScript. It is like any other
variable, the only difference is that an object holds multiple values in
terms of properties and methods.
▪ Properties can hold values of primitive data types and methods are
functions.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 40
JavaScript object
❑ In JavaScript, an object is a standalone entity because there is no class
in JavaScript.
❑ In JavaScript, an object can be created in two ways:
1.Object literal
2.Object constructor

JavaScript Object by object literal

object={property1:value1,property2:value2.....propertyN:valueN}

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 41
JavaScript object
var emptyObject = {}; // object with no properties or methods

var laptop = { brand: “Dell“,price:32000 }; // object with single property

// object with single method


var message = {
showMessage: function (val) {
alert(val);
}
};

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 42
JavaScript object
// object with properties & method
var person = {
firstName: “VNR",
lastName: “VJIET",
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

Note : You must specify key-value pair in object for properties or methods.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 43
Access JavaScript Object Properties & Methods

You can access object properties in two ways:

1. objectName.propertyName

2.objectName["propertyName"]

Demo

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 44
Object Constructor
The second way to create an object is with Object Constructor
using new keyword.

var person = new Object();

// Attach properties and methods to person object


person.firstName = "Malige";
person["lastName"] = "Gangappa";
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 45
JavaScript array

Array constructor

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 46
Array Literals

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 47
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 48
Return
The original array elements in reverse order.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 49
Math object
All methods and properties can be used without creating a Math object first.
The syntax for Math any methods is : Math.method.(number)

Math.ceil(x) Returns x rounded up to its nearest integer


Math.floor(x) Returns x rounded down to its nearest integer
Math.sign(x) returns if x is negative, null or positive
Math.pow(x, y) returns the value of x to the power of y
Math.sqrt(x) returns the square root of x
Math.abs(x) returns the absolute (positive) value of x
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 50
Questions
Loop

1. Find all even numbers between start and end numbers


2. Determine the composite number
3. find the average of numbers between 1 and 10

If condition
1. Find the biggest of three numbers
2. Print the personality based on age
3. Print the student grade based on score in a test

1. JavaScript Program to Check Palindrome Number


2. JavaScript to print multiplication table
3. Demonstrate JavaScript Array indexOf() Method

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 51
String Object

The JavaScript string is an object that represents a sequence of characters. String


object wraps JavaScript's string primitive data type with a number of helper methods.

There are 2 ways to create string in JavaScript


1.By string literal
2.By string object (using new keyword)

1) By string literal
var stringName = "string value";

2) By string object (using new keyword)

var stringname=new String("string literal");

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 52
String Object

String Properties :

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 53
Examples

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 54
Regular Expression Object

❑ The RegExp ( Regular Expression ) is an Object to define a pattern for


searching or manipulating strings.
❑ A regular expression is a sequence of characters that forms a search
pattern.
❑ Regular expressions can be used to perform all types of text
search and text replace operations.

/pattern/attributes;

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 55
Syntax

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 56
Metacharacters

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 57
Metacharacters

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 58
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 59
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 60
❑ Why DOM?
❑ HTML is used to structure the web pages and JavaScript is used to add behavior to our
web pages. When an HTML file is loaded into the browser, the javascript can not
understand the HTML document directly. So it interprets and interacts with the
Document Object Model (DOM), which is created by the browser based on the HTML
document.
❑ What is DOM?
❑ The Document Object Model (DOM) is an application programming interface (API) for
manipulating HTML documents.
❑ The DOM represents an HTML document as a tree of nodes. The DOM provides
functions that allow you to add, remove, and modify parts of the document effectively.
Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 61
Consider the following HTML document:

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 62
DOM
Document Object has properties
methods
Using this, we can
❑ Select HTML elements
❑ Modify HTML elements
❑ Remove/delete HTML elements
❑ Add/remove styles to HTML elements

Methods to select HTML elements:


1. document.getElementById(“id”)
selects an element by element id
2. document.getElementsByClassName(“name”)

Returns list of all elements belong to the specified class

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 63
Methods to select HTML elements:

3. document.getElementsByTagName(“name”);

Returns all elements by tag name

4. document.querySelector(“.class” |”#id” | “tagname”);

Returns the first object matching the CSS style


selector

5. document.querySelectorAll(“.class” |”#id” | “tagname”);

Returns the first object matching the CSS style


selector

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 64
❑ Get the parent element
❑ Get child elements
❑ Get siblings of an element

To get the parent node of a specified node in the DOM tree, you use the parentNode
property:

let parent = node.parentNode;

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 65
<body>
<div id="main"> Output

<p class="note">This is a note!</p>


</div>
<script>
let note = document.querySelector('.note’);
console.log(note.parentNode);
</script>
</body>

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 66
To get the first child element of a specified element, you use the firstChild property of the
element:
let firstChild = parentElement.firstElementChild;

Example:

let content = document.getElementById('menu’);


let firstChild = content.firstElementChild;
console.log(firstChild);

Output:

<li class="first">Home</li>
Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 67
let lastChild = parentElement.lastElementChild;

Get all child elements

let children = parentElement.children;

selects all child elements of the element with the Id menu:

let menu = document.getElementById('menu');


let children = menu.children;
console.log(children);

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 68
1.document.createElement(“Node”)

This method creates new HTML element.


2.append() – inserts a node after the last child node.

Assume that you have the following HTML:


<div id="app"></div>
You can use the append() method to append a text to an element:
let app = document.querySelector('#app');
app.append(‘Text Demo');
Output HTML:
console.log(app.textContent);
<div id="app"> Text Demo</div>

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 69
3. innerHTML – get and set the HTML content of an element.

To get the HTML markup contained within an element, you use the following syntax:
let content = element.innerHTML;
Example:
get the content of the <ul> element:
<ul id="menu">
<li>Home</li> let menu = document.getElementById('menu');
<li>Services</li>
</ul> console.log(menu.innerHTML);

Output:

<li>Home</li>
<li>Services</li>
Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 70
❑ An HTML web page has finished loading
❑ An HTML button was clicked.
The above statements are actions on web page.
These actions are called an events.

An HTML event can be something the browser does, or something a user does.

Who generates the events?

1. User Mouse clicks, keyboard press, focus on element etc.

2. System Web page loading, abort,error etc.

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 71
1. Mouse Events
Event Performed Event Handler Description
click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over


the element
mouseout onmouseout When the cursor of the mouse leaves an
element
mousedown onmousedown When the mouse button is pressed over
the element
mouseup onmouseup When the mouse button is released over
the element
mousemove onmousemove When the mouse movement takes place.

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 72
2. KeyBoard Events
Event Performed Event Handler Description
Keydown onkeydown When the user release the key
Keyup onkeyup When the user press the key
3.Window/Document events
Event Performed Event Handler Description
load onload When the browser finishes the loading of the
page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the
browser
Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 73
4. Form events

Event Performed Event Handler Description


focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form
element
change onchange When the user modifies or changes the
value of a form element

Dr.M.Gangappa,Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 74
Data validation
<form >
<input type = “text” name=“name” value=“”>
<input type = “text” name=“age” value=“”>
<input type =“submit” value=“submit”>
</form>
<script>
var name = document.forms[0].elements[0].value; // extract the value
var age= document.forms[0].elements[1].value; // data for age
</script>
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 75
Date object

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 76
Date object

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 77
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 78
Questions

1. Write a JavaScript to print the current day and current month.


2. Write a JavaScript to greet a day…Good morning, Good
afternoon, Good evening.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 79
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 80
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 81
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 82
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 83
Window object methods

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 84
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 85
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 86
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 87
Object hierarchy

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 88
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 89
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 90
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 91
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 92
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 93
Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 94
EVENTS
Examples of events
➢An HTML web page has finished loading
➢An HTML input field was changed
➢An HTML button was clicked

❑ JavaScript's interaction with HTML is handled through events that


occur when the user or the browser manipulates a page.
❑ Events are a part of the Document Object Model (DOM)
❑ Every HTML element contains a set of events which can trigger JavaScript
Code.

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 95
Syntax
HTML allows event handler attributes, with JavaScript code.

Syntax <element event='some JavaScript'>

Demo

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 96
Event types:

➢Mouse-related: mouse movement, button click, enter/leave element


➢Keyboard-related: down, up, press
➢Input field events :Input field changed, Form submitted
➢Miscellaneous:
✓ Page loaded/unloaded
✓ Image loaded
✓ Uncaught exception

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 97
1.Inline event handling:

<button onclick=“console.log(‘button was clicked’);”>click me!</button>

<button onclick = "console.log('button was clicked');alert(('hello')">click me!</button>

2. Event Handling using JavaScript:

node.event = () => {
// handling statements
}

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 98
Example:

App.js
Index.html
// accessing btn1
let btn1 = document.querySelector("#btn1"); <body>
<button id="btn1">click me!</button>
<script src="App.js"></script>
</body>
btn1.onclick=()=>{
console.log("button1 was clicked");

// Square root of a number


let a = parseInt(prompt("enter value"));
console.log(Math.sqrt(a));

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 99
Event Listeners in JavaScript
The addEventListener() method is used to attach an event handler to a particular
element.

element.addEventListener(event, function);

let btn1 = document.queryselector("#btn1");


btn1.addEventListener("click", change);
function change(){
Document.body.style.backgroundColor=“blue”;
}

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 100
END of JavaScript

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 101
Practice Questions
1. Print the output generated by the script below:
<html>
<body>
<button id="btn1">click me!</button>
<script>
let btn1 = document.querySelector("#btn1");
btn1.onclick = () => { document.write("button event handler 1 is performed"); }
btn1.onclick= () => { document.write("button event handler 2 is performed"); }
</script>
</body>
</html>

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 102
Practice Questions
2.Determine the colors applied for the text "Good morning":
<html > <head> <style>
.red { background-color: red; }
.blue { background-color: blue; }
.orange { background-color: orange; }
.green { background-color: orange; }
</style>
</head>
<body>
<h1 class="blue green orange red ">Good morning</h1>
</body>
</html>

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 103
XML

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 104
What is XML
➢ XML stands for eXtensible Markup Language that you can use
to create your own tags.
➢ A markup language is used to provide information about a
document.
➢ HTML tags tell a browser how to display the document.
➢ XML tags give a reader some idea what some of the data
means.

Dr Malige Gangappa CSE dept VNR VJIET


Dr Malige Gangappa CSE dept VNR VJIET
XML Tree
XML documents form a tree structure that starts at "the root" and branches to "the
leaves"

Dr Malige Gangappa CSE dept VNR VJIET


An Example XML Document

Dr Malige Gangappa CSE dept VNR VJIET


The XML prolog is optional. If it exists, it must come first in the
document. Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
Well-Formed XML Documents
A well-formed document must adher to the following rules:
➢ There must be exactly one root element.
➢ Every start tag has a matching end tag.
➢ Elements may be nested.
➢ Attribute values must be quoted.
➢ An element may not have two attributes with the same
name.
➢ Comments and processing instructions may not appear
inside tags.
➢ No unescaped < or & signs may occur inside character
data. Dr Malige Gangappa CSE dept VNR VJIET
Valid XML Documents
A "well formed" XML document is not the same as a "valid" XML
document.
A "valid" XML document must be well formed. In addition, it
must conform to a document type definition.

There are two different document type definitions that can be


used with XML:
➢ DTD - The original Document Type Definition
➢ XML Schema - An XML-based alternative to DTD

Dr Malige Gangappa CSE dept VNR VJIET


XML DTD
➢ An XML document with correct syntax is called "Well Formed".
➢ An XML document validated against a DTD is both "Well Formed" and
"Valid".

What is a DTD?
DTD stands for Document Type Definition that defines the structure and
the legal elements and attributes of an XML document.

DTD Types:
1. Internal DTD
2. External DTD
Dr Malige Gangappa CSE dept VNR VJIET
When a DTD is declared within the file it is called Internal DTD and if
it is declared in a separate file it is called External DTD.
External DTD: You can put the DTD in a separate file from the XML
file, and refer to it using a <!DOCTYPE ...> line at the beginning of
the XML file.
Internal DTD: You can put the DTD inside the <!DOCTYPE ...>
declaration at the front of the XML file.
Syntax for internal DTD
<?xml version='1.0’?>
<!DOCTYPE root-element-name [
dtd-declarations ...
Dr Malige Gangappa CSE dept VNR VJIET
]>
XML Document Internal DTD
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE note [
<note> <!ELEMENT note (to,from,heading,body)>
<to>Ravi</to> <!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<from>Krishna</from>
<!ELEMENT heading (#PCDATA)>
<heading>Reminder</heading>
<!ELEMENT body (#PCDATA)>
<body> ]>
Don't forget me this weekend!
</body> <note>
</note> <to>Ravi</to>
<from>Krishna</from>
<heading>Reminder</heading>
<body>
Xml document Don't forget me this weekend!
validation </body>
</note>

Dr Malige Gangappa CSE dept VNR VJIET


External DTD

Dr Malige Gangappa CSE dept VNR VJIET


Dr Malige Gangappa CSE dept VNR VJIET
DTD declarations
1. Element type declaration

In a DTD, elements are declared with an ELEMENT declaration.

Syntax: <!ELEMENT element_name content >

content: EMPTY, ANY, (#PCDATA), child element, mixed .

EMPTY :The element is declared to be an empty as the following:


<!ELEMENT empty_element EMPTY>
e.g., <empty_element></empty_element>
e.g., <empty_element />Dr Malige Gangappa CSE dept VNR VJIET
ANY: The element can have any element or character data.
<!ELEMENT element_name ANY>
e.g.,
<element_name>
This is a line of characters.
<other_element> ... </other_element>
</element_name>

(#PCDATA): The content can be only character data.

<!ELEMENT first (#PCDATA)>

e.g.,
<first> vnr vjiet </first>
Dr Malige Gangappa CSE dept VNR VJIET
mixed: The content may contain character data and/or child elements.
<!ELEMENT mix_element (#PCDATA | first | last)>

Dr Malige Gangappa CSE dept VNR VJIET


child elements:
Syntax (i): <!ELEMENT a (x,y,z)>

The element “a” must have an element x, followed by y,


followed by z
Syntax (ii): <!ELEMENT b (x|y|z)>
The element “b” must have an element x, or y, or z

Dr Malige Gangappa CSE dept VNR VJIET


Modifiers:
➢ An asterisk(*) stands for zero or more.
➢ plus sign(+) stands for one or more.
➢ question mark(?) stands for zero or one.
e.g.
<!ELEMENT c (x*, y+, z?) >

Dr Malige Gangappa CSE dept VNR VJIET


Declaring Only One Occurrence of an Element
<!ELEMENT element-name (child-name)>
Example:
<!ELEMENT note (message)>

Declaring Minimum One Occurrence of an Element


<!ELEMENT element-name (child-name+)>
Example:
<!ELEMENT note (message+)>

Dr Malige Gangappa CSE dept VNR VJIET


Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
Weaknesses of DTDs
DTDs are rather weak specifications by DB & programming-language standards

Only one base type: PCDATA


No useful “abstractions”, e.g., sets
IDs and IDREFs are untyped
No constraints

Dr Malige Gangappa CSE dept VNR VJIET


Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
What is an XML Schema?
❑ An XML Schema describes the structure of an XML document.
❑ The XML Schema language is also referred to as XML Schema Definition (XSD).
❑ One of the greatest strength of XML Schemas is the support for data types.

XML Schema Data types


There are two types of data types in XML schema.
1. simpleType
2. complexType

❑ The complex type contains other elements.


❑ The simple types do not contain other elements or attributes.

Dr Malige Gangappa CSE dept VNR VJIET


Advantages of using XML Schema over DTD

❑ Schema uses XML as language so you don’t have to learn new


syntax.
❑ XML schema supports data types and namespaces.
❑ You can use XML parser to parse the XML schema as well.
❑ Just like XML, the XML schema is extensible which means you can
reuse the schema in other schema, as well as you can reference
more than one schemas in a single XML document.

Dr Malige Gangappa CSE dept VNR VJIET


XML Namespaces
❑ XML Namespaces provide a method to avoid element name conflicts.

If these XML fragments were added together, there would be a name conflict. Both contain
a <table> element, but the elements have different content and meaning.

Solving the Name Conflict Using a Prefix


Name conflicts in XML can easily be avoided using a name prefix.

Dr Malige Gangappa CSE dept VNR VJIET


This XML carries information about an HTML table, and a piece of furniture:

In the example above, there will be no conflict because the two <table> elements have
different names.
Dr Malige Gangappa CSE dept VNR VJIET
XML Namespaces - The xmlns Attribute
The namespace can be defined by an xmlns attribute in the start tag of an element.
The namespace declaration has the following syntax xmlns:prefix="URI".

Dr Malige Gangappa CSE dept VNR VJIET


XSD - The <schema> Element
The <schema> element is the root element of every XML Schema.

xmlns:xs="http://www.w3.org/2001/XMLSchema"

It specifies that the elements and data types that come from the
"http://www.w3.org/2001/XMLSchema" namespace should be prefixed with xs:

Dr Malige Gangappa CSE dept VNR VJIET


XSD Complex Elements
A complex element contains other elements and/or attributes.

There are four kinds of complex elements:


➢ empty elements
➢ elements that contain only other elements
➢ elements that contain only text
➢ elements that contain both other elements and text

How to Define a Complex Element

Dr Malige Gangappa CSE dept VNR VJIET


XML Schema definition for the above XML document

Dr Malige Gangappa CSE dept VNR VJIET


Complex Empty Elements
<product prodid="1345" />

XSD - declaration

<xs:element name="product">
<xs:complexType>
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
</xs:element>

Dr Malige Gangappa CSE dept VNR VJIET


Complex Text-Only Elements

<shoesize country="france">35</shoesize>

XSD-declaration
<xs:element name="shoesize">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="country" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>

Dr Malige Gangappa CSE dept VNR VJIET


Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
XML Element Mixed Content
Write XML Schema definition for the following xml document?

Solution:

Dr Malige Gangappa CSE dept VNR VJIET


XSD Indicators

There are seven indicators:

Order indicators:
•All Sequence Indicator
•Choice The <sequence> indicator specifies that the
•Sequence child elements must appear in a specific
order:
Occurrence indicators:
•maxOccurs <xs:element name="person">
•minOccurs <xs:complexType>
<xs:sequence>
Group indicators: <xs:element name="firstname" type="xs:string"/>
•Group name
<xs:element name="lastname" type="xs:string"/>
•attributeGroup name
</xs:sequence>
</xs:complexType>
Dr Malige Gangappa CSE dept VNR VJIET
Write the xml schema definition to validate the following xml document?

<?xml version="1.0"?>
<beginners book>
<to>My Readers</to>
<from>Chaitanya</from>
<subject>A Message to my readers</subject>
<message>Welcome to beginnersbook.com</message>
</beginnersbook>

Dr Malige Gangappa CSE dept VNR VJIET


Save this XML file: bb.xml
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.vnrvjiet.in">

<xs:element name="beginnersbook">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="subject" type="xs:string"/>
<xs:element name="message" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

Dr Malige Gangappa CSE dept VNR VJIET


Dr Malige Gangappa CSE dept VNR VJIET
Dr Malige Gangappa CSE dept VNR VJIET
XML DOM

The XML DOM is:


➢A standard object model for XML
➢A standard programming interface
for XML
➢Platform- and language-independent
➢A W3C standard
The XML DOM is used to get, change, add, or delete XML
elements from xml document.

Xml document DOM


NOTE : All XML elements can be accessed through the XML DOM.
Dr Malige Gangappa CSE dept VNR VJIET
According to the XML DOM, everything in an XML document is
a node:
➢ The entire document is a document node
➢ Every XML element is an element node
➢ The text in the XML elements are text nodes
➢ Every attribute is an attribute node
➢ Comments are comment nodes

Dr Malige Gangappa CSE dept VNR VJIET


nodes
➢ Parent nodes
➢ Child nodes
➢ Sibling nodes
➢ In a node tree, the top node is called the root
➢ Every node, except the root, has exactly one parent
node
➢ A node can have any number of children
➢ A leaf is a node with no children
➢ Siblings are nodes with the same parent

Accessing the nodes


Dr Malige Gangappa CSE dept VNR VJIET
Accessing Nodes

➢ By using the getElementsByTagName() method


➢ By navigating the node tree, using the node
relationships.
The getElementsByTagName() Method
getElementsByTagName() returns all elements with a specified tag name.

Syntax
node.getElementsByTagName("tagname");

The following example returns all <title> elements under the x element:
example x.getElementsByTagName("title");
Dr Malige Gangappa CSE dept VNR VJIET
Navigating Node Relationships
var x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
// display the information
document.getElementById("demo").innerHTML = x.nodeValue;

Three important node properties are:


1. nodeName
2. nodeValue
3. nodeType

Dr Malige Gangappa CSE dept VNR VJIET


Node properties

1. The documentElement property of the XML document is the


root node.
2. The nodeName property of a node is the name of the node.
3. The nodeType property of a node is the type of the node.

Node type Node name


example
1 Element node
2 Attribute node Exampl2 nodetype
3 Text node
bookstore
8 Comment
9 Document
Dr Malige Gangappa CSE dept VNR VJIET
AJAX
What is AJAX?
❑AJAX = Asynchronous JavaScript And XML.

❑AJAX is not a programming language.

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 159
AJAX Introduction
❑ A synchronous request blocks the client until operation completes i.e.
browser is unresponsive. In such case, javascript engine of the browser
is blocked.
❑ An asynchronous request doesn’t block the client i.e. browser is
responsive. In such case, javascript engine of the browser is not
blocked.

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 160
❑ A synchronous request blocks the client until operation completes i.e.
browser is unresponsive. In such case, javascript engine of the browser is
blocked.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 161
❑ An asynchronous request doesn’t block the client i.e. browser is
responsive. In such case, javascript engine of the browser is not
blocked.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 162
❑ AJAX stands for Asynchronous JavaScript and XML.
❑ It is not a programming language but it is a web browser technology for
creating better, faster, and more interactive web applications with the
help of XML, HTML, CSS, and Java Script.
❑ AJAX applications might use XML to transport data.
❑ AJAX allows to send and receive data asynchronously without reloading
the web page. So it is fast.

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 163
Examples of AJAX

A list of some famous web applications that make use of AJAX:

❑ Google Maps
A user can drag an entire map by using the mouse, rather than clicking on a button.

❑ Gmail
Gmail is a webmail built on the idea that emails can be more efficient and useful.

❑ Yahoo Maps
Now it's even easier and more fun to get where you're going!

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 164
How AJAX Works
AJAX communicates with the server using XMLHttpRequest object.
XMLHttpRequest object plays a important role.

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 165
How AJAX Works

1.User sends a request from the UI and a javascript call goes to


XMLHttpRequest object.
2.HTTP Request is sent to the server by XMLHttpRequest object.
3.Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4.Data is retrieved.
5.Server sends XML data data to the XMLHttpRequest callback function.
6.HTML and CSS data is displayed on the browser.

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 166
AJAX - The Object
The XMLHttpRequest object can be used to exchange data with a server
behind the scenes.

It performs following operations:


1.Sends data from the client in the background
2.Receives the data from the server
3.Updates the webpage without reloading it.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 167
XMLHttpRequest Object Methods
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
open(method,url,async,user,psw) Specifies the request
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false
(synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 168
XMLHttpRequest Object Properties
Property Description
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 169
AJAX - Request
To send a request to a server, we use the open() and send() methods of
the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt", true);


xhttp.send();

Method Description
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)
send() Sends the request to the server

Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 170
AJAX - Response
❑ The readyState property holds the status of the XMLHttpRequest.
❑ The status property and the statusText property holds the status of
the XMLHttpRequest object.
Property Description
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
403: "Forbidden"
404: "Page not found"
statusText Returns the status-text (e.g. "OK" or "Not Found")
Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 171
THANK YOU

Prepared by M.Gangappa , Department of Computer Science & Engineering, VNRVJIET, Hyderabad February 22, 2025 172

You might also like