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

UNIT 3 JS and AJAX (1)

This is a unit 3 of Web technology which includes JS and AJAX helps students to prepare for exams.

Uploaded by

prashants1546
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

UNIT 3 JS and AJAX (1)

This is a unit 3 of Web technology which includes JS and AJAX helps students to prepare for exams.

Uploaded by

prashants1546
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

UNIT 3 (PART 1)

JAVA SCRIPT

• It is an Object Oriented Language.


• An object is a real world thing which has state and
behaviour.
• It has implicit object only (pre-defined; object definition
is defined)
• It is a loosely coupled Language. (No need to declare
variable or define data type)
• It is an interpreted & case sensitive language
• It can be directly embedded with HTML (with the help of
script tag within head tag or body tag).
• Complementary to and integrated with Java and HTML.
Java Script Syntax
• The <script> Tag: In HTML, JavaScript code must be inserted between <script> and
</script> tags.

<html>
<head>
<script language="javascript" type="text/javascript">
//java script functions
</script>
</head>
<body>
<script language="javascript" type="text/javascript">
//java script functions
</script>
</body>
</html>
Example
<html>
<body>
<script language="javascript">
document.write("Hello World!");
</script>
</body>
</html>
Objects

• Java Script object is a collection of –


a) DataTypes – properties
b) Function Types- methods

• Objects appear internally & externally. Eg. Maths,


Boolean, String, Dates, Array, Number, Functions.
JavaScript Entities
1. Primitive Types: Stores the values-

• Number
• String
• Boolean (true or false value)
• Null (reserved word, means no value)
• Undefined (Variable declared without value will
have the value undefined, no keyword used)
2. Pre- defined objects: They provide properties and
methods to be used by Primitives. Also known as
wrapper objects. Objects contain address at which
value is stored.

• Eg. Number, String, Boolean


JavaScript Statements
• JavaScript statements has: Literals, Operators,
Expressions, Keywords, Comments, Identifiers and
Variables.
• JavaScript ignores spaces, tabs, and newlines that
appear in JavaScript programs.
• JavaScript statements are followed by a semicolon
character. (Optional)
• Eg. var a;
Comments in JavaScript
• Any text between a // and the end of a line is treated
as a comment.

• Any text between the characters /* and */ is treated


as a comment. This may span multiple lines.

• JavaScript also recognizes the HTML comment


opening sequence <!- - and closing sequence - ->.
Literals (Fixed Values)
1. Numeric Literals (Numbers – integer, floating point,
double precision floating point)

2. String Literals (‘abc’, “abc”)


Variables
• JavaScript variables are containers for storing data
values. (Local& Global)

• The general rules:


 Names can contain letters, digits, underscores,
and dollar signs.
 Names must begin with a letter , $ and _
 Names are case sensitive
 Reserved words cannot be used as names
• We can declare a JavaScript variable with
the var keyword.
• Eg. var a,b,c;
JavaScript Data Types
• JavaScript allows us to work with three primitive data
types:

 Numbers eg. 123, 120.50 etc.


 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false
Reserved Words, Operators, if –else, switch,
for, while, do –while, goto, break, continue
document.write Property (to display
text)
1. document.write(“hello”);

2. var a = “Hii”;
document.write(a);
document.write(“<b>” + a + “</b>”);

3. document.write (typeof "ABC"); // output - String


• We can enable or disable JavaScript from settings
option in web Browsers.

• JavaScript can be used for Client-side developments


as well as Server-side developments
JavaScript Functions
• A JavaScript function is a block of JavaScript code
that can be executed to perform a particular task.

• For example, a function can be executed when


an event occurs, like when the user clicks a button.
Function Definition:

<script type="text/javascript">
function functionname (parameter-list)
{
Statements
}
</script>

Calling a Function:

<script type="text/javascript">
functionname ();
</script>
• Eg.

<html>
<head>
<script type = "text/javascript">
function a()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<form>
<input type = "button" onclick = "a()" value = "Say Hello">
</form>
</body>
</html>
• Function Parameters
• The return Statement
JavaScript HTML method
getElementById()

1. document.getElementById(“id_name").innerHTML- To change the element


content.

<html>
<body>
<p id="demo" onclick = "a()"> My First Paragraph</p>
<script language = "javascript">
function a()
{
document.getElementById ("demo").innerHTML = 5 + 6;
}
</script>
</body>
</html>
2. document.getElementById ("t").style.color -CSS

Eg.
document.getElementById ("t").style.color = “RED”;
3. document.getElementById ("t").value - To change the element
value.

<html>
<head>
<script language = "javascript">
function sum()
{
a = parseInt(document.getElementById("t").value);
b = parseInt(document.getElementById("t1").value);
c = a+b;
document.getElementById("t2").value = c;
}
</script>
</head>
<body>
A = <input type="text" id= "t"> <br>
B = <input type="text" id= "t1"> <br>
SUM= <input type="text" id= "t2"> <br><br><br>
<input type="Button" value="sum" onclick="sum()">
</body>
</html>
Pop up Boxes
1. Alert Dialog Box:

An alert dialog box is mostly used to give a warning


message to the users. If one input field requires to
enter some text but user does not enter anything,
then as validation you can use alert box to give
warning message.
<html>
<head>
<script type="text/javascript">
alert("Warning Message");
</script>
</head>
</html>
2. Confirmation Dialog Box:

A confirmation dialog box is used to take user's consent


on any option. It displays dialog box with two buttons:

OK and Cancel
<html>
<body>
<script>
var msg;
if (confirm("Press a button!") == true)
msg = "You pressed OK!";
else
msg = "You pressed Cancel!";
document.write(msg);
</script>
</body>
</html>
3. Prompt Dialog Box:

It is used to accept input from user and is implicit Java


script function. It has 2 buttons (OK and CANCEL) and 1
text field.
<html>
<head>
<script type="text/javascript">
var a = prompt("Enter your name : ", "your name
here");
document.write(a);
</script>
</head>
</html>
HTML EVENTS
• An HTML event can be something the browser does, or something a user does. Eg.

1.
<html>
<head>
<script language="javascript">
function a()
{
alert("Hello");
}
</script>
</head>
<body>
<input type="Button" value="Click" onclick="a()">
</body>
</html>
TIME INTERVALS
1. setTimeout() – It is used to call another function in given time
period.

setTimeOut(“Function_name()”,Time);
// function to be called, time in milliseconds

• This function is called inside the function which it is calling.

function ab()
{
setTimeout(“ab()”,1000);
}
2. setInterval() – It is used to call another function in given time
period.

setInterval(“Function_name()”,Time);
/ function to be called, time in milliseconds

• This function is called inside the function which it is calling.

function a()
{
a = setInterval(“ab()”,1000);
}
3. clearInterval() –This function is used to clear interval
of setInterval function & stop its functionality. It is not
associated with setTimeout().

Eg. clearInterval(a);
• Example : Stop Watch
<html>
<head>
<script language="javascript">
var a;
function a()
{
a = setInterval("Start()",1000);
}

i=0; function Start()


{
i++;
document.getElementById("t").innerHTML =i;
}
function Stop()
{
clearInterval(a);
}
</script>
</head>
<body>
<b id="t"> 0 </b><br><br>
<input type="Button" value="Start" onclick="a()">
<input type="Button" value="Stop" onclick="Stop()">
</body>
</html>
OBJECTS
1. Math Object - It allows performing mathematical tasks. It includes several mathematical methods.

sqrt(num)

floor(num)

min(a,b)

max(a,b)

sin(num)

log(num)

eg. document.write (math.min ( 4.5,7.0 ) ); // 4.5

2. Boolean Object-

b = new Boolean(False/True/Empty);

eg. b = false;

document.write(b.toString());
3. String Object - String object have many useful string
related functionalities. Some methods are:

concat(str) – concatenates 2 strings.


s.toLowerCase()

Eg.
var s1 = “Hello”;
document.write(s1.concat(“world”));
document.write(s1.charAt(0));
4. Number Object -

• Primitive values (like 3.14), cannot have properties and


methods (because they are not objects). But with
JavaScript, methods and properties are also available to
primitive values, because JavaScript treats primitive
values as objects when executing methods and
properties.

• toString() returns a number as a string.

x.toString(); // Eg. var x = 123;


5. Date Object- It picks system Date. It work with dates
(years, months, days, hours, minutes, seconds,
milliseconds)

Ob = new Date(); // Date() is constructor of Date function


Date Get & Set Methods

• getSeconds()
• getMinutes()
• getHours()
• getDay()
• getMonths()
• getYears()
• getTime()

Similarly to set date.

Eg1.
<script>
var d = new Date();
d.setDate(20);
document.write(d);
</script>
• Eg2. Digital Watch
<html>

<head>

<script language="javascript">

var a;

function a()

d = new Date();

h = d.getHours();

m = d.getMinutes();

s = d.getSeconds();

if(h<10)

h = '0' + h;

if(m<10)

m = '0' + m;

if(s<10)

s = '0' + s;

document.getElementById("t").innerHTML = h + ":" + m + ":" + s;

setTimeout("a()",1000);

</script>

</head>

<body onload = "a()">

<b id = "t"> HH:MM:SS </b>

</body>

</html>
6. Array Object

JavaScript arrays are used to store multiple values. It


can hold more than one value at a time.

var a = new Array();

eg. var cars = new Array ("Volvo", "BMW");


// Cars [0] return Volvo.
Arrays are Objects

• Arrays are a special type of objects. Arrays use numbers to access its
"elements".
• Objects use names to access its "members".

In this example, person.firstName returns John


var person = {firstName:"John", lastName:"Doe", age: 46};

Array Properties and Methods

cars.length; cars.sort(); cars.push("Hello"); cars.reverse();


• 7. JavaScript RegExp Object
Type Conversions
• By the use of a JavaScript function

• Automatically by JavaScript itself

Converting Numbers to Strings

 String (123) or (123).toString() // returns "123"

Converting Booleans to Strings

 false.toString() or String(false) // returns "false"

Converting Strings to Numbers

 Number ("3.14") // returns 3.14 or parseFloat()

 Number (" ") // returns 0 parseInt()

 Number("") // returns 0

 Number("99 88") // returns NaN (not a no.)

Converting Booleans to Numbers

 Number (false) // returns 0

 Number (true) // returns 1


JavaScript Errors
Throw and Try to Catch

• The try statement lets you test a block of code for


errors.
• The catch statement lets you handle the error.
• The throw statement lets you create custom errors.
• The finally statement lets you execute code, after try
and catch, regardless of the result.
Java Java script
Java is an OOP programming language Java Script is an OOP scripting language
Java code needs to be compiled. JavaScript code are all in text.
Java code allows programmer full JavaScript code contains limited number of
functionality and needs to be compiled. commands and features.
Java is high-level, static,compiled JavaScript is text
and strongly type language. based , dynamic and weakly typed language.
In Java there is different datatypes like
In JavaScript there is var keyword is used to
int, float, string, etc and we have to
define variable and according to value it takes
specify datatype with variable while
datatype of that variable automatically.
declaring.
Java program has file extension “.Java”
and after compilation it becomes “.class” JavaScript file has file extension “.js”.
file that contains bytecode
Making changes is tough Comparatively easy to make changes
Write once run anywhere Depends on browser support
• Calculator
AJAX (Asynchronous JavaScript and
XML)
• Classic web pages, (which do not use AJAX) must reload the
entire page if the content should change.
• AJAX is a technique for creating fast and dynamic/interactive
web pages.
• Update a web page without reloading the page
• Request data from a server - after the page has loaded
• Receive data from a server - after the page has loaded
• Examples of applications using AJAX: Google Maps, Gmail,
YouTube, and Facebook.
• Uses HTML for content, CSS for presentation, DOM and
JavaScript for dynamic content display.
AJAX is Based on Internet Standards

• XMLHttpRequest object (to retrieve data from a web


server)
• JavaScript/DOM (to display/use the data)
Steps of AJAX Operation
1. A client event occurs
2. An XMLHttp Request object is created
3. The XMLHttp Request object is configured
4. The XMLHttp Request object makes an asynchronous
request to the web server.
5. Webserver returns the result containing XML
document.
6. The XMLHttp request object calls the callback()
function and processes the result.
7. The HTML DOM is updated.
How AJAX Works
AJAX - Create an XMLHttpRequest Object

• All modern browsers support the XMLHttpRequest object and have it in-
built.
• The XMLHttpRequest object is used to update parts of a web page,
without reloading the whole page.

Syntax:

• variable = new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:

• variable = new ActiveXObject ("Microsoft.XMLHTTP");


Eg.

<html>

<head>

<script language="javascript" >

var x;

function a()

if (window.XMLHttpRequest) // code for modern browsers

x = new XMLHttpRequest();

else // code for IE6, IE5

x = new ActiveXObject("Microsoft.XMLHTTP");

x.onreadystatechange = function()

if (x.readyState = = “4” && x.status = = “200”)

document.getElementById("t").innerHTML = x.responseText;

x.open("GET", "abc.txt", true);

x.send();

</script>

</head>

<body>

<input type = ”Button” value = "hello" onclick = "a()">

<b id="t"></b>

</body>

</html>
AJAX - Send a Request To a Server
• The XMLHttpRequest object is used to exchange data
with a server.
• To send a request to a server, we use the open() and
send() methods of the XMLHttpRequest object:

Method Description

method: the type of request: GET or POST


open(method, url, async) url: the server (file) location
async: true (asynchronous) or false (synchronous)

send() Sends the request to the server (used for GET)

send(string) Sends the request to the server (used for POST)


AJAX - Server Response
• To get the response from a server, use responseText
or responseXML property of the XMLHttpRequest
object.

Property Description

ResponseText get the response data as a string

ResponseXML get the response data as XML data


The onreadystatechange event

Property Description

Stores a function (or the name of a function) to be called


onreadystatechange
automatically each time the readyState property changes

Holds the status of XMLHttpRequest. Changes from 0 to


4:
0: request not initialized
ReadyState 1: server connection established
2: request received
3: processing request
4: request finished and response is ready

200: "OK"
Status
404: Page not found

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy