0% found this document useful (0 votes)
18 views118 pages

UNIT 3

This document provides an overview of web scripting languages, focusing on JavaScript, AJAX, and jQuery. It covers the fundamentals of JavaScript, including its syntax, data types, and functionalities like DOM manipulation and event handling. Additionally, it explains the differences between client-side and server-side scripting, along with practical examples and best practices for implementing JavaScript in web applications.

Uploaded by

Amol Rajpure
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)
18 views118 pages

UNIT 3

This document provides an overview of web scripting languages, focusing on JavaScript, AJAX, and jQuery. It covers the fundamentals of JavaScript, including its syntax, data types, and functionalities like DOM manipulation and event handling. Additionally, it explains the differences between client-side and server-side scripting, along with practical examples and best practices for implementing JavaScript in web applications.

Uploaded by

Amol Rajpure
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/ 118

Subject: Web Application Development

(314453)

UNIT NO. 03
Web Scripting Language
Syllabus : Unit 2: Web Scripting
Language
JavaScript: Introduction to Scripting languages, Introduction to JavaScript
(JS), JS Variables and Constants.
AJAX: Why AJAX, Call HTTP Methods Using AJAX, Data Sending, Data
Receiving, AJAX Error Handling.

JQUERY :Why JQuery, How to Use, DOM Manipulation with Jquery.


Web Scripting Language
• Scripting Language: Used to write a script, A
command that are executed without the need of
compiler but with the help of interpreter.
• Instruction are directly executed.
• Used in Web application.
• Types: 1. Server Side Scripting Language (e.g.: SQL,
PHP, Perl etc.
2. Client Side Scripting Language (e.g.
JavaScript, AJAX, JQuery)
Web Scripting Language

• Client Side Scripting: All calculations are done by


computer user.
• Client side scripts are downloaded by the browser,
interpreted by the browser, executed by the
browser, depending on the memory, CPU speed of
user computer.
• Light-weight, less full-featured language.
Web Scripting Language

• Server Side Scripting: All calculations are done by


the server your website id hosted on.
• The script is interpreted by the supported
language parser, like PHP or ASP.
• Server side script are browser independent.
• Server side script are secure.
Introduction to JavaScript
• Overview of JavaScript,
• JS variable Scope and Constant
• using JS in an HTML (Embedded, External),
• Data types,
• Control Structures,
• Arrays,
• Functions
• Objects
Overview of
JavaScript
• JavaScript is one of the 3 languages all web developers
must
learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

• JavaScript is a very powerful client-side scripting language.

• Javascript is a dynamic computer programming language.


JavaScrip
•tJavaScript is a front-end scripting language developed by
Netscape for dynamic content

• Lightweight, but with limited capabilities

6
• Can be used as object-oriented language
• Client-side technology
• Embedded in your HTML page
• Interpreted by the Web browser
• Simple and flexible
• Powerful to manipulate the DOM (Document Object Mode)
JavaScript
Advantages
• JavaScript allows interactivity such as:
• Implementing form validation
• React to user actions, e.g. handle keys

7
• Changing an image on moving mouse over it
• Sections of a page appearing and disappearing
• Content loading and changing dynamically
• Performing complex calculations
• Custom HTML controls, e.g. scrollable table
• Implementing AJAX functionality
What Can JavaScript
•Do?
Can handle events
• Can read and write HTML elements
• Can validate form data
• Can access / modify browser cookies

8
• Can detect the user’s browser and OS
• Can be used as object-oriented language
• Can handle exceptions
• Can perform asynchronous server calls
(AJAX)
JavaScript
Syntax
• JavaScript can be implemented using <script>... </script> HTML
tags in a web page.
• Place the <script> tags, within the <head> tags.

• Syntax:
• <script language="javascript" type="text/javascript">
• JavaScript code
• </script>
JavaScript
Syntax
• Example:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
• The comment ends with a "//-->". Here "//" signifies a comment
in JavaScript
• Output
Hello World!
JavaScript
Syntax
The JavaScript syntax is similar to C# and Java
• Operators (+, *, =, !=, &&, ++, …)

• Variables (typeless)

12
• Conditional statements (if, else)

• Loops (for, while)

• Arrays (my_array[]) and associative arrays


(my_array['abc'])

• Functions (can return value)

• Function variables (like the C# delegates)


Enabling JavaScript in
Browsers
• JavaScript in Firefox

• Open a new tab → type about: config in the address bar.

• Then you will find the warning dialog.

• Select I’ll be careful, I promise!

• Then you will find the list of configure options in the


browser.

• In the search bar, type javascript.enabled.

• There you will find the option to enable or disable


javascript by right-clicking on the value of that option →
select toggle.
JavaScript Editor and
Extension
Use Notepad to write the code

Save the document using .html (if


embedded JavaScript)

Save document with .js (if external


JavaScript)

Run the code in brower


JavaScript - Placement
in HTML File
• There is a flexibility given to include JavaScript code
anywhere
in an HTML document.
• However the most preferred ways to include JavaScript in
an HTML file are as follows −

• Script in <head>...</head> section.


• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in
<head>...</head> section.
JavaScript in <head>...</head>
section
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") }
//--> </script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello"
/>
</body>
</html>

• This code will produce the following results −


JavaScript in <body>...</body>
section
<html>
<head> </head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

• This code will produce the following results



Hello World
This is web page body
JavaScript in <body> and
<head>
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") } //-->
</script>
</head>
<body>
<script type="text/javascript">
<!-- document.write("Hello World") //-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body> </html>

• This code will produce the following result −


JavaScript in External
File
• HTML File
<html>
<head>
<script type="text/javascript" src="filename.js"
>
</script>
</head>
<body> ....... </body>
</html>

• JavaScript File – filename.js


function sayHello()
{ alert("Hello World") }
The First
first-script.html
Script
<html>

<body>

20
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>

</html>
Another Small
Example
small-example.html
<html>

<body>
<script type="text/javascript">

21
document.write('JavaScript rulez!');
</script>
</body>

</html>
Using JavaScript
Code
• The JavaScript code can be placed in:
• <script> tag in the head
• <script> tag in the body – not recommended
• External files, linked via <script> tag the head

22
• Files usually have .js extension
• Highly recommended
• The .js files get cached by the browser

<script src="scripts.js" type="text/javscript">


<!– code placed here will not be executed! -->
</script>
JavaScript – When is
Executed?
• JavaScript code is executed during the page loading or when
the browser fires an event
• All statements are executed at page loading
• Some statements just define functions that can be called later

23
• Function calls or code can be attached as "event handlers" via
tag attributes
• Executed when the event is fired by the browser

<img src="logo.gif" onclick="alert('clicked!')" />


Calling a JavaScript Function
from Event Handler – Example
<html> image-onclick.html
<head>
<script type="text/javascript">
function test (message)

24
{
alert(message);
}
</script>
</head>

<body>
<<img src="vpcoe_Black_Transparent
LOGO.png"onclick="test('clicked!')" />
</body>
</html>
Using External Script
• Using external script files:
Files
<html> external-JavaScript.htm
<head>
l
<script src="sample.js" type="text/javascript">
</script>
The <script> tag is always

25
</head>
<body> empty.
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
</html>
• External JavaScript file:
function sample() {
alert('Hello from sample.js!')
}
sample.js
Data
•Types
JavaScript data types:
• Numbers (integer, floating-point)
• Boolean (true / false)
• String type – string of characters

26
var myName = "You can use both single or double
quotes for strings";
• Arrays
var my_array = [1, 5.3, "aaa"];

• Associative arrays (hash tables)


var my_hash = {a:2, b:3, c:"text"};
Everything is
Object
• Every variable can be considered as object
• For example strings and arrays have member functions:
objects.html

27
var test = "some string";
alert(test[7]); // shows letter 'r'
alert(test.charAt(5)); // shows letter 's'
alert("test".charAt(1)); //shows letter 'e'
alert("test".substring(1,3)); //shows 'es'

var arr = [1,3,4];


alert (arr.length); // shows 3
arr.push(7); // appends 7 to end of array
alert (arr[3]); // shows 7
String
Operations
• The + operator joins
strings
string1 = "fat ";
string2 = "cats";

28
alert(string1 + string2); // fat cats

• What is "9" + 9?
alert("9" + 9); // 99

• Converting string to
number:
alert(parseInt("9") + 9); // 18
Arrays Operations and
Properties
• Declaring new empty
array:
var arr = new Array();
• Declaring an array holding few
var arr = [1, 2, 3, 4, 5];
elements:

29
• Appending an element / getting the last
element:
arr.push(3);
var element = arr.pop();
• Reading the number of elements (array
length):
arr.length;
• Finding element's index in the
array:
arr.indexOf(1);
Standard Popup
•Boxes
Alert box with text and [OK] button
• Just a message shown in a dialog box:
alert("Some text here");

30
• Confirmation box
• Contains text, [OK] button and [Cancel]
button:
confirm("Are you sure?");

• Prompt box
• Contains text, input field with default value:

prompt ("enter amount", 10);


JavaScript
Variables
<script
type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Sum of Numbers –
sum-of-numbers.html
Example
<html>

<head>
<title>JavaScript Demo</title>

32
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum;
}
</script>
</head>
Sum of Numbers – Example
sum-of-numbers.html (cont.)
(2)
<body>
<form name="mainForm">
<input type="text" name="textBox1" /> <br/>
<input type="text" name="textBox2" /> <br/>

33
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>

</html>
JavaScript Prompt –
prompt.htm
Example
lprice = prompt("Enter the price", "10.00");
alert('Price + VAT = ' + price * 1.2);

34
JavaScript -
Operators
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary)
Operators
Conditional Statement
(if)
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}

36
Symbol Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal
!= Not equal
Switch
Statement
• The switch statement works like in
C#:
switch (variable) { switch-statements.htm
case 1:
l
// do something

37
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
Switch case
Example
Loop
s• Like in C#
• for loop
• while loop

39
• do … while
loop
var counter;
for (counter=0; counter<4; counter++)
{
alert(counter);
}
while (counter < 5)
{
alert(++counter);
loops.html
}
While-loop
Example
• <html>
• <body>
• <script type="text/javascript">
• <!-- var count = 0;
• document.write("Starting Loop ");
• while (count < 10){
• document.write("Current Count : " + count + "<br
/>"); count++; }
• document.write("Loop stopped!");
• //--> </script>
• <p>Set the variable to different value and then
try...</p>
</body> </html>
Function
s• Code structure – splitting code into parts
• Data comes in, processed, result
returned
Parameters come

41
function average(a, b, c) in here.
{
var total; Declaring variables
total = a+b+c; is optional. Type is
return total/3; never declared.
}
Value returned
here.
Function Arguments & Return
Value
• Functions are not required to return a value
• When calling function it is not obligatory to specify all of its
arguments
• The function has access to all the arguments

42
passed via arguments array

function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));

functions-demo.html
JavaScript Function
Syntax
• function name(parameter1, parameter2, parameter3) {
code to be executed
}

• var x = myFunction(4, 3); // Function is called, return value


will end up in x

function myFunction(a, b) {
return a * b; // Function returns the product of
and b a
}
Advanced JavaScript: JSON -
Introduction
• JSON stands for JavaScript Object Notation
• JSON is a text format for storing and transporting data
• JSON is "self-describing" and easy to understand
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent
Why Use JSON?
• The JSON format is syntactically similar to the code for
creating JavaScript objects. Because of this, a JavaScript
program can easily convert JSON data into JavaScript
objects.
• Since the format is text only, JSON data can easily be sent
between computers, and used by any programming
language.
• JavaScript has a built in function for converting JSON
strings into JavaScript objects:
• JSON.parse()
• JavaScript also has a built in function for converting an
object into a JSON string:
• JSON.stringify()
JSON Syntax
• The JSON syntax is a subset of the JavaScript syntax.
• JSON syntax is derived from JavaScript object notation
syntax:
1. Data is in name/value pairs
2. Data is separated by commas
3. Curly braces hold objects
4. Square brackets hold arrays

JSON Data - A Name and a Value


JSON data is written as name/value pairs (key/value pairs).

A name/value pair consists of a field name (in double quotes), followed by a


colon, followed by a value:

Example
"name":“Sachin"
JSON Create
Data Types used in JSON
1. Number: {e.g. “age”:32}
2. String : e.g ."name":“Sachin"
3. Boolean : e.g. {“sales”:true}
4. Array : e.g. “employees”: [“Sachin”, ”Rahul”, “satish”]
5. Value: It can be string, a number, true or false, null.
6. Object: Unorder collection of key:value pairs.
e.g. {“employees”: { “name”:“Sachin”, ”age”:32, “city”:”pune”]
7. Null: empty values on JSON can be null
e.g. {“middlename”:null}
JSON Vs XML
JSON Example
{"employees":[
{"name":"Shyam", "email":"[email protected]"},
{"name":"Bob", "email":"[email protected]"},
{"name":"Jai", "email":"[email protected]"}
]}
The XML representation of above JSON example is
<employees> <employee>
<name>Shyam</name>
<email>[email protected]</email>
</employee> <employee>
<name>Bob</name>
<email>[email protected]</email>
</employee> <employee>
<name>Jai</name>
<email>[email protected]</email>
</employee> </employees>
JSON Vs XML
Uses of JSON
• Writing a script JavaScript base application that includes
browser extensions and websites.
• For serializing and transmitting structured data over
network connection.
• To transmit data between server and web application
• Web services and API’s use JSON format to provide public
data.
• In modern programming language.
Technologies used in Traditional Web
Programming: (SPPU EXAM 18, 19, 6/8 Marks)
1. Programming Languages: ways to communicate to
computers and tell them what to do.
1. Javascript - used by all web browsers, Meteor, and lots of other
frameworks.
2. Coffeescript - is a kind of “dialect” of javascript. It is viewed as simpler
and easier on your eyes as a developer but it complies (converts) back
into javascript
3. Python -used by the Django framework and used in a lot of
mathematical calculations
4. Ruby - used by the Ruby on Rails framework
5. PHP - used by Wordpress
6. Go - newer language, built for speed.
7. Objective-C - the programming language behind iOS (your iPhone), lead
by Apple
8. Swift - Apple’s newest programming language
9. Java - Used by Android (Google) and a lot of desktop applications.
Technologies used in Traditional Web
Programming:
2. Framework: Frameworks are built to make building and
working with programming languages easier.
1. Node.js - a server-side javascript framework
2. Ruby on Rails - a full-stack framework built using ruby
3. Django - a full-stack framework built using python
4. Phonegap / Cordova - a mobile framework that exposes native api’s of iOS
and Android for use when writing javascript
5. Bootstrap - a UI (user interface) framework for building with
HTML/CSS/Javascript
6. Foundation - a UI framework for building with HTML/CSS/Javascript
7. Wordpress - a CMS (content management system) built on PHP.
Currently, about 20% of all websites run on this framework
8. Drupal - a CMS framework built using PHP.
9. .NET - a full-stack framework built by Microsoft
10. Angular.js - a front-end javascript framework.
11. Ember.js - a front-end javascript framework.
12. Backbone.js - a front-end javascript framework.
Technologies used in Traditional Web
Programming:
3. Libraries : Libraries are groupings of code snippets to enable a large
amount of functionality without having to write it all by yourself.
E.g. jQuery

4. Databases: Databases are where all your data is stored.


1. MongoDB - is an open-sourced NoSQL database and is currently the only
database supported by Meteor.
2. Redis - is the most popular key-value store. It is lighting fast for
retrieving data but doesn’t allow for much depth in the data storage.
3. PostgreSQL - is a popular open-sourced SQL database.
4. MySQL - is another popular open-sourced SQL database. MySQL is used
in Wordpress websites.
5. Oracle - is an enterprise SQL database.
6. SQL Server - is an SQL server manager created by Microsoft.
Technologies used in Traditional Web
Programming:
5. Protocols: Protocols are standardized instructions for how to
pass information back and forth between computers and devices.

1. HTTP - This protocol is how each website gets to your browser.


Whenever you type a website like “http://google.com” this
protocol requests the website from google’s server and then
receives a response with the HTML, CSS, and javascript of the
website.

2. REST - is a protocol mainly used for API’s. It has standard


methods like GET, POST, and PUT that let information be
exchanged between applications.
Technologies used in Traditional Web
Programming:
6. Data formats: Data formats are the structure of how data is
stored.
1. JSON - is quickly becoming the most popular data format
2. XML - was the main data format early in the web days and
predominantly used by Microsoft systems
3. CSV - is data formatted by commas. Excel data is typically
formatted this way.
JSON Key-Value pair
• Two primary parts that make up ae keys and values.
Key: It is always a string enclosed in quotation marks.
Value: It can a number, string,Boolean expression, array or
object.

• Writing the JSON format on multiple lines often makes it


much more readable, especially when dealing with a large
data set.

• Example:
{
"first_name" : "Sammy",
"last_name" : "Shark",
"online" : true
}
JSON Access:
• JSON data is normally accessed in Javascript through dot
notation. let’s consider the JSON object sammy:
var sammy = {
"first_name" : "Sammy",
"last_name" : "Shark",
"online" : true
}
• In order to access any of the values, we’ll be using dot
notation that looks like this:
sammy.first_name
sammy.last_name
sammy.online

The variable sammy is first, followed by a dot, followed by


the key to be accessed.
JSON Access:
• To create a JavaScript alert that shows us the value
associated with the key first_name in a pop-up, we can
do so by calling the JavaScript alert() function:
• alert(sammy.first_name);

• Output
Sammy
JSON Array
• Inside the JSON string there is a JSON array literal:

["Ford", "BMW", "Fiat"]


Arrays in JSON are almost the same as arrays in JavaScript.
In JSON, array values must be of type string, number, object, array, boolean or null.

Example: <!DOCTYPE html>


<html>
<body>
<h2>Creating an Array from a Literal</h2>
<p id="demo"></p
<script>
const myArray = ["Ford", "BMW", "Fiat"];
document.getElementById("demo").innerHTML = myArray;
</script>
</body>
JSON Array
• You can create a JavaScript array by parsing a JSON string:

Example: <!DOCTYPE html>


<html>
<body>

<h2>Creating an Array from JSON</h2>


<p id="demo"></p>

<script>
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myArray;
</script>

</body>
</html>
JSON Array
Accessing Array Values:

You access array values by index:


<!DOCTYPE html>
<html>
<body>

<h1>Access an Array by Index</h1>


<p id="demo"></p>

<script>
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myArray[0];
</script>

</body>
</html>
JSON Array
Arrays in Objects
Objects can contain arrays:
Example
{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}

You access array values by index:

myObj.cars[0];
JS Arrow Functions
• Syntax
let myFunction = (arg1, arg2, ...argN) => { statement(s) }
Here,
myFunction is the name of the function
arg1, 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:
let myFunction = (arg1, arg2, ...argN) => expression
• 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 to regular functions.
• Example,
// function expression
let x = function(x, y) {
return x * y;
}
can be written as using an arrow function
// using arrow functions
let x = (x, y) => x * y;
JS Callback Functions
• A callback is a function passed as an argument to another function.
• This technique allows a function to call another function
• A callback function can run after another function has finished
• JavaScript functions are executed in the sequence they are called.
Example:

function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {


let sum = num1 + num2;
myCallback(sum); • myDisplayer is a called a callback function.
} • It is passed to myCalculator() as an argument.

myCalculator(5, 5, myDisplayer);

Output: 10
JS Promises
• A Promise is a JavaScript object that links producing code and consuming code
• "Producing code" is code that can take some time
• "Consuming code" is code that must wait for the result.
• ECMAScript 2015, also known as ES6, introduced the JavaScript Promise object.
• The first browser version with full support for Promise objects:
Chrome 33 Edge 12 Firefox 29 Safari 7.1 Opera 20
Feb, 2014 Jul, 2015 Apr, 2014 Sep, 2014 Mar, 2014
Promise Syntax:

let myPromise = new Promise(function(myResolve, myReject) {


// "Producing Code" (May take some time)
When the producing code
obtains the result, it should call
myResolve(); // when successful
one of the two callbacks:
myReject(); // when error
});
Result Call
Success myResolve(result value)
// "Consuming Code" (Must wait for a fulfilled Promise)
Error myReject(error object)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
JS Promises
When the producing code obtains the result, it should call one of the two
callbacks:

Result Call
Success myResolve(result value)
Error myReject(error object)

A JavaScript Promise object can be:

• Pending
• Fulfilled
• Rejected
myPromise.state myPromise.result
"pending" undefined
"fulfilled" a result value
"rejected" an error object
JS Promises
• how to use a Promise:
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Example: <script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// some code (try to change x to 5)
if (x == 0) {
myResolve("OK");
} else {
Output:
myReject("Error");
} OK
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
</script>
JS Async-Await Functions
• async makes a function return a Promise
• await makes a function wait for a Promise

Async Syntax:
async function myFunction() {
return "Hello";
}
Is the same as:
function myFunction() {
return Promise.resolve("Hello");
}
Here is how to use the Promise:
myFunction().then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
JS Async-Await Functions
Example:
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}

async function myFunction() {return "Hello";}

myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
</script>

Output:
Hello
JS Async-Await Functions
Await Syntax:

The await keyword can only be used inside an async function.

let value = await promise;


Example:
<!DOCTYPE html>
<html>
<body>
<h1 id="demo"></h1>
<script>
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("Hello How are you?");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
</script>
</body>
</html>
JS Error Handling
• JavaScript does not give compile-time errors.
• you will get a runtime error for accessing an undefined variable or calling
undefined function etc.

• Syntax:

try
{
// code that may throw an error
}
catch(ex)
{
// code to be executed if an error occurs
}
finally{
// code to be executed regardless of an error occurs or not
}
JS Error Handling
• Example:
Output:
<!DOCTYPE html>
Error: ReferenceError: Sum is not defined
<html>
<body>
finally block executed
<p id="errorMessage">Error: </p>
<p id="message"></p>
<script>
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML += ex;
}
finally{
document.getElementById("message").innerHTML = "finally block executed";
}
</script>
</body>
JS Error Handling
• throw: Use throw keyword to raise a custom error.
• Example:
<!DOCTYPE html> Output:
<html> Error occurred
<body>
<p id="errorMessage"></p>

<script>
try
{
throw "Error occurred";
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}

</script>
</body>
</html>
AJAX- Introduction
• AJAX = Asynchronous JavaScript And XML(Extensible Markup Language).

• AJAX is not a programming language.

• AJAX just uses a combination of:


• A browser built-in XMLHttpRequest object (to request data from a web
server)
• JavaScript and HTML DOM (to display or use the data)
• How AJAX Works:
Working of AJAX
(a) Classic web application model (b) Ajax web application model.
Working of AJAX
(a) Classic web application model (b) Ajax web application model.
Why AJAX ?
Call HTTP Methods Using AJAX
SPPU Exam

• The heart of AJAX is the XMLHttpRequest object.


1. Create an XMLHttpRequest object
2. Define a callback function
3. Open the XMLHttpRequest object
4. Send a Request to a server

The XMLHttpRequest Object

• to exchange data with a web server behind the scenes.


• i.e it is possible to update parts of a web page, without
reloading the whole page.
Call HTTP Methods Using AJAX
1. Create an XMLHttpRequest object:
• Syntax:
variable = new XMLHttpRequest();
• All modern browsers have a built-in XMLHttpRequest object.
2. Define a Callback Function
• A callback function is a function passed as a parameter to
another function.
• In this case, the callback function should contain the code to
execute when the response is ready.
xhttp.onload = function() {
// What to do when the response is ready
}
Call HTTP Methods Using AJAX
3. Send a Request
• To send a request to a server, you can use the open() and
send() methods of the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Example
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();

// Define a callback function


xhttp.onload = function() {
// Here you can use the Data
}

// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Call HTTP Methods Using AJAX
XMLHttpRequest Object Methods:
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method, url, async, Specifies the request
user, psw) 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
Used for GET requests
send(string) Sends the request to the server.
Used for POST requests
Call HTTP Methods Using AJAX
XMLHttpRequest Object Properties
Property Description
onload Defines a function to be called when the request is recieved
(loaded)
onreadystatechange Defines a function to be called when the readyState property
changes
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

responseXML Returns the response data as XML data

status Returns the status-number of a request


200: "OK"
403: "Forbidden"
404: "Not Found"

statusText Returns the status-text (e.g. "OK" or "Not Found")


Call HTTP Methods Using AJAX
XMLHttpRequest Object Properties

The XMLHttpRequest object is the developers dream, because you can:

• 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

• Send data to a server in the background


Data Sending and Receiving data in AJAX

• $.ajax() method allows you to send asynchronous http requests to

submit or retrieve data from the server without reloading the whole

page.

• $.ajax() can be used to send http GET, POST, PUT, DELETE etc.

request. It can retrieve any type of response from the server.

• Syntax: $.ajax(url,[options])

• Use option parameter to customize ajax request as per your need.


Data Sending and Receiving data in AJAX
Steps of AJAX Operation:
1. A client event occurs.
2. An XMLHttpRequest object is created.
3. The XMLHttpRequest object is configured.
4. The XMLHttpRequest object makes an asynchronous request to the
Webserver.
5. The Webserver returns the result containing XML document.
6. The XMLHttpRequest object calls the callback() function and
processes the result.
7. The HTML DOM is updated.
Data Sending and Receiving data in AJAX
1. A Client Event Occurs:
• A JavaScript function is called as the result of an event.
• Example − validateUserId() JavaScript function is mapped as an event
handler to an onkeyup event on input form field whose id is set
to "userid"
• <input type = "text" size = "20" id = "userid" name = "id" onkeyup =
"validateUserId();">.
Data Sending and Receiving data in AJAX
1. A Client Event Occurs:
Example:
try {
var ajaxRequest; // The variable that ajaxRequest = new
makes Ajax possible! ActiveXObject("Microsoft.XMLHTTP
");
function ajaxFunction() { } catch (e) {
try { // Something went wrong
alert("Your browser broke!");
// Opera 8.0+, Firefox, Safari return false;
ajaxRequest = new XMLHttpRequest(); }
}
} catch (e) { }
// Internet Explorer Browsers }
try {
ajaxRequest = new
ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
Data Sending and Receiving data in AJAX
2. The XMLHttpRequest Object is Configured:

• a function that will be triggered by the client event and a callback function
processRequest() will be registered.

function validateUserId() {
ajaxFunction();

// Here processRequest() is the callback function.


ajaxRequest.onreadystatechange = processRequest;

if (!target) target = document.getElementById("userid");


var url = "validate?id=" + escape(target.value);

ajaxRequest.open("GET", url, true);


ajaxRequest.send(null);
}
Data Sending and Receiving data in AJAX
3. Making Asynchronous Request to the Webserver:
• using the XMLHttpRequest object ajaxRequest.
ajaxRequest.onreadystatechange = processRequest;

function validateUserId() {
ajaxFunction();

// Here processRequest() is the callback function.


ajaxRequest.onreadystatechange = processRequest;

if (!target) target = document.getElementById("userid");


var url = "validate?id = " + escape(target.value);

ajaxRequest.open("GET", url, true);


ajaxRequest.send(null);
}

Assume you enter Zara in the userid box, then in the above request, the URL is
set to "validate?id = Zara".
Data Sending and Receiving data in AJAX
4. Webserver Returns the Result Containing XML Document

You can implement your server-side script in any language:


Steps:
• Get a request from the client.
• Parse the input from the client.
• Do required processing.
• Send the output to the client.
Data Sending and Receiving data in AJAX
5. Callback Function processRequest() is Called

• state change to the readyState of the XMLHttpRequest object.


• it sets a variable message on true or false based on the returned value
from the Webserver.

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
Data Sending and Receiving data in AJAX

6. The HTML DOM is Updated


• your HTML page will be updated. It happens in the following way −

1. JavaScript gets a reference to any element in a page using DOM API.


2. The recommended way to gain a reference to an element is to call.
AJAX Error Handling
When we request to server we didn’t get proper response (HTTP Status 200) as
per our expectation. For ex. we can get
1) Internal Server Error
2) Network Connection Error
3) Page Not Found Error,
4) Access Denied Error.

Use AJAX error function.


$.post(url,
data,
function (response) {

}
).error(function (jqXHR, textStatus, errorThrown) {

alert(formatErrorMessage(jqXHR, errorThrown));

}
);
AJAX Error Handling
1) jqXHR : This variable will contain status code and we can access by
“jqXHR.status”.
2) textStatus : Response in text like Success.
3) errorThrown : Some time error may be related to parse error, timeout error so
these error message will come under this variable.

alert(formatErrorMessage(jqXHR, errorThrown));
1) alert : Simple. using to show error message
2) formatErrorMessage : We are using this function to parse this variable and get
exact error and to show a proper message to user.
jQuery -
Introduction
• jQuery is a JavaScript Library.
• jQuery greatly simplifies JavaScript programming.
• jQuery is a lightweight
• jQuery also simplifies a lot of the complicated things
from JavaScript, like AJAX calls and DOM manipulation.
• The jQuery library contains the following features:
• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX
• Utilities
Adding jQuery to Your
Web Pages
• There are several ways to start using jQuery on your
web
site. You can:
• Download the jQuery library from jQuery.com
• Include jQuery from a CDN, like Google
Downloading
jQuery
• There are two versions of jQuery available for downloading:
• Production version - this is for your live website because it
has been minified and compressed
• Development version - this is for testing and development
• Both versions can be downloaded from jQuery.com.
• The jQuery library is a single JavaScript file, and you
reference it with the HTML <script> tag (notice that the
<script> tag should be inside the <head> section):
<head>
<script src="jquery-3.2.1.min.js"></script>
</head>
• Tip: Place the downloaded file in the same directory as
the pages where you wish to use it.
jQuery
CDN
• If you don't want to download and host jQuery yourself, you
can include it from a CDN (Content Delivery Network).
• Both Google and Microsoft host jQuery.
• To use jQuery from Google or Microsoft, use one of the
following:
• Google CDN:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
>
</script>
</head>
jQuery
Syntax
• With jQuery you select (query) HTML elements and
perform "actions" on them.
• syntax :
• $(selector).action()
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)
• Examples:
• $(this).hide() - hides the current element.
• $("p").hide() - hides all <p> elements.
• $(".test").hide() - hides all elements with class="test".
• $("#test").hide() - hides the element with id="test".
jQuery
Selectors-Selecting
elements
• jQuery selectors allow you to select and manipulate
HTML element(s).
• jQuery selectors are used to "find" (or select) HTML
elements based on their name, id, classes, types, attributes,
values of attributes and much more. It's based on the
existing CSS Selectors, and in addition, it has some own
custom selectors.
• All selectors in jQuery start with the dollar sign
and parentheses: $().
The element
Selector
• The jQuery element selector selects elements based on the
element name.
• You can select all <p> elements on a page like this:
• $("p")
• Example
• When a user clicks on a button, all <p> elements will be
hidden:
• $(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The #id
Selector
• The jQuery #id selector uses the id attribute of an HTML tag to find
the specific element.
• An id should be unique within a page, so you should use the #id
selector when you want to find a single, unique element.
• To find an element with a specific id, write a hash
character, followed by the id of the HTML element:
• $("#test")
• Example
• When a user clicks on a button, the element with id="test" will be
hidden:
• $(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
jQuery css() Method- Changing
Style
• jQuery css() Method
• The css() method sets or returns one or more style
properties for the selected elements.
• Return a CSS Property
• To return the value of a specified CSS property, use
the following syntax:
• css("propertyname");
• Set a CSS Property
• To set a specified CSS property, use the following
syntax:
• css("propertyname","value");
Changing Style-
Return a CSS Property
Example
<html><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></s
c ript>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
});
</script>
</head><body>
<p style="background-color:#ff0000">This is a paragraph.</p>
<button>Return background-color of p</button>
</body></html>
Changing Style-
Return a CSS Property Example
o/p
Output of Previous Code
Changing Style-
Set a CSS Property
Example
<html><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script
>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p style="background-color:#ff0000">This is a paragraph.</p>
<button>Set background-color of p</button>
</body></html>
Changing Style-
Set a CSS Property Example
o/p
Output of Previous Code

After clicking on button


jQuery - Add
Elements
• We will look at four jQuery methods that are used to add
new content:
• append() - Inserts content at the end of the
selected elements
• prepend() - Inserts content at the beginning of
the selected elements
• after() - Inserts content after the selected elements
• before() - Inserts content before the selected
elements
jQuery append() Method-
Example
<html><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></scri
p t>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("ol").append("<li> List item 3 </li>");
}); }); </script>
</head>
<body> After Clicking on button
<ol>
<li>List item 1</li>
<li>List item 2</li>
</ol>
<button id="btn1"> Append list items </button>
</body></html>
jQuery - Remove
Elements
• Remove Elements/Content
• To remove elements and content, there are mainly two
jQuery methods:
• remove() - Removes the selected element (and
its child elements)
• empty() - Removes the child elements from the
selected element
jQuery remove() Method-
Example
• <html > <head>
• <script
src="https://code.jquery.com/jquery-1.10.2.js">
</script>
• </head>
• <body>
• <p>Hello</p>
• how are you?
• <script> After Clicking on button
• <button>Remove </button>
• $( "button" ).click(function()
{
• $( "p" ).remove();
• });
• </script>
• </body></html>
DOM Manipulation with JQuery
• Document Object Model (DOM) - is a W3C (World Wide Web
Consortium) standard that allows us to create, change, or remove elements
from the HTML or XML documents.
• Query provides methods such as attr(), html(), text() and val() which act as
getters and setters to manipulate the content from HTML documents.
• Basic operations which you can perform on DOM elements with the help of
jQuery standard library methods −
1. Extract the content of an element
2. Change the content of an element
3. Adding a child element under an existing element
4. Adding a parent element above an existing element
5. Adding an element before or after an existing element
6. Replace an existing element with another element
7. Delete an existing element
8. Wrapping content with-in an element
DOM Manipulation with JQuery
1. jQuery - Get Content: jQuery provides html() and text() methods to extract
the content of the matched HTML element.

Synatx : $(selector).html();
$(selector).text();
The jQuery text() method returns plain text value of the content where
as html() returns the content with HTML tags.

Example:
Dynamic Content Change with JQuery
How to handle events in dynamically created elements in jQuery ?
<!DOCTYPE html>
<html>
<head>
<title>
How to handle events in dynamically created elements in jQuery?
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("#list li").on("click", function (event) { $('#list').append('<li>New Paragraph</li>');
}); });
</script> <style>
li {
font-size: 30px;
width: 400px;
padding: 20px;
color: green;
}
</style> </head> <body>
<!-- Click on this paragraph -->
<ul id="list">
<li>Click here to append !!!</li>
</ul>
</body>
</html >
Dynamic Content Change with JQuery
How to handle events in dynamically created elements in jQuery ?

On first, second ….. Mouse click, following output will display in web browser:
UI Design Using JQuery
• jQuery UI is a curated(online content) set of user interface interactions,
effects, widgets, and themes built on top of the jQuery JavaScript Library.
• For building highly interactive web applications.
• four groups i.e. interactions, widgets, effects, utilities.
• open-source library that contains different animation effects and widgets
• It can be used with almost all browsers.
• Download & Installation: (https://jqueryui.com/),
• File Structure:

• Example: add a date picker to a form control, jQuery UI is a perfect choice.


UI Design Using JQuery
• Download & Installation: (https://jqueryui.com/),
Create an HTML file like index.html and add file links inside head section of
code.
<link rel=”stylesheet” href=”jqueryui/jquery-ui.min.css”>
<script src=”jqueryui/external/jquery/jquery.js”></script>
<script src=”jqueryui/jquery-ui.min.js”></script>

• Using CDN Link: Without downloading the jQuery UI files, you can include
CDN links inside the head section to run your code.
<link href=”https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css”
rel =”stylesheet”>
<script src=”https://code.jquery.com/jquery-1.10.2.js”></script>
<script src=”https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>.

You might also like