0% found this document useful (0 votes)
19 views24 pages

Unit3 Part1 Notes Javascript_ajax

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
19 views24 pages

Unit3 Part1 Notes Javascript_ajax

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 24

Unit 3 part1

JavaScript Introduction:
JavaScript is the Scripting Language for the Web.
JavaScript can update and change both HTML and CSS.
JavaScript can calculate, manipulate and validate data.
Uses of Javascript:
 Validation: JavaScript can be used to validate HTML forms, such
as checking if required fields are filled out, or if a date is
valid. JavaScript can validate many different fields, including
passwords, email addresses, and mobile numbers.
 Calculation: JavaScript can be used for calculations. For
example:Program to add two numbers in javascript and html
 Animation: JavaScript can be used for animation.For
example:aumatically changing images after sometime in
website.
 Some other uses of javascript

Advantages of Javascript
 Simplicity ‒ having a simple structure makes JavaScript easier
to learn and implement, and it also runs faster than some
other languages.
 Speed ‒ JavaScript executes scripts directly within the web
browser without connecting to a server first or needing a
compiler. Additionally, most major browsers allow JavaScript to
compile code during program execution.
 Versatility ‒ JavaScript is compatible with other languages like
PHP, Perl, and Java. It also makes data science and machine
learning accessible to developers.
 Server load ‒ another perk of operating on the client-side is that
JavaScript reduces the requests sent to the server.

JavaScript HTML DOM Document:


The HTML DOM document object is the owner of all other objects in
your web page.

 When an HTML document is loaded into a web browser, it becomes


a document object.
 The document object is the root node of the HTML document.
 The document object is accessed with:
 window.document or just document

The HTML DOM Document Object


The document object represents your web page.
If you want to access any element in an HTML page, you always
start with accessing the document object.

Finding HTML Elements

Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Document Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p id="intro">Finding HTML Elements by Id</p>
<p>This example demonstrates the getElementsById
method.</p>
<p id="demo"></p>
<script language =”javascript”>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is: " + element.innerHTML;
</script>
</body>
</html>

Output:
JavaScript HTML DOM
Finding HTML Elements by Id
This example demonstrates the getElementsById method.
The text from the intro paragraph is: Finding HTML Elements by
Id

Forms:
An HTML form is used to collect user input. The user input is
most often sent to a server for processing.
The <form> Element
The HTML <form> element is used to create an HTML form for
user input:
The <input> Element
The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending
on the type attribute.
Here are some examples:
Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of


many choices)

<input Displays a checkbox (for selecting zero or


type="checkbox"> more of many choices)

<input Displays a submit button (for submitting the


type="submit"> form)

<input type="button"> Displays a clickable button


Form Attribute:1)The Action Attribute
The action attribute defines the action to be performed when
the form is submitted.
Usually, the form data is sent to a file on the server when the
user clicks on the submit button.
In the example below, the form data is sent to a file called
"action_page.php". This file contains a server-side script that
handles the form data:
Example
On submit, send form data to "action_page.php":
<form action="/action_page.php">
2) Method attribute:
The Method Attribute
The method attribute specifies the HTTP method to be used when
submitting the form data.
The form-data can be sent as URL variables (with method="get") or as HTTP
post transaction (with method="post").
The default HTTP method when submitting form data is GET.
Example
This example uses the GET method when submitting the form data:
<form action="/action_page.php" method="get">

Form example of user registration in HTML


<Html>
<head>
<title>
Registration Page
</title>
</head>
<body bgcolor="Lightskyblue">
<br>
<br>
<form action=”aa.php” method=”get/post”>
<label> Firstname </label>
<input type="text" name="firstname" size="15"/> <br> <br>
<label> Middlename: </label>
<input type="text" name="middlename" size="15"/> <br> <br>
<label> Lastname: </label>
<input type="text" name="lastname" size="15"/> <br> <br>
<label>
Course :
</label>
<select>
<option value="Course">Course</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>
<br>
<br>
<label>
Gender :
</label><br>
<input type="radio" name="male"/> Male <br>
<input type="radio" name="female"/> Female <br>
<input type="radio" name="other"/> Other
<br>
<br>
<label>
Phone :
</label>
<input type="text" name="country code" value="+91" size="2"/
>
<input type="text" name="phone" size="10"/> <br> <br>
Address
<br>
<textarea cols="80" rows="5" value="address">
</textarea>
<br> <br>
Email:
<input type="email" id="email" name="email"/> <br>
<br> <br>
Password:
<input type="Password" id="pass" name="pass"> <br>
<br> <br>
Re-type password:
<input type="Password" id="repass" name="repass"> <br> <br>
<input type="button" value="Submit"/>
</form>
</body>
</html>

Output:

Java script code simple program:


< html >
< body >
<p>
< script language=”javascript” > document.write(“My first
JavaScript”)
< /script >
< /p >
< /body >
< /html >

Alert Box

An alert box is often used if you want to make sure information


comes through to the user. When an alert box pops up, the user will
have to click "OK" to proceed.

Syntax
alert("sometext");

Confirm Box
A confirm box is often used if you want the user to verify or accept
something.

When a confirm box pops up, the user will have to click either "OK"
or "Cancel" to proceed. If the user clicks "OK", the box returns true.
If the user clicks "Cancel", the box returns false.

Syntax

confirm("sometext");

Prompt Box

A prompt box is often used if you want the user to input a value
before entering a page.

When a prompt box pops up, the user will have to click either "OK"
or "Cancel" to proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user
clicks

"Cancel" the box returns null. Syntax


prompt("sometext","defaultvalue");

JavaScript Statements

A JavaScript statement is a command to a browser. The purpose of


the command is to tell the browser what to do.

This JavaScript statement tells the browser to write "Hello Dolly" to


the web page:

document.write("Hello Dolly");

JavaScript Comments

Comments can be added to explain the JavaScript, or to make the


code more readable. Single line comments start with //.

JavaScript Multi-Line Comments


Multi line comments start with /* and end with */.

Javascript variables :

Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:


a)Automatically b)Using var c) Using let d)Using const

Note
The var keyword was used in all JavaScript code from 1995 to
2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older
browsers.
Var example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"> </p>
<script language=”javascript”>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
Output:
JavaScript Variables
In this example, x, y, and z are variables.
The value of z is: 11

Let Example: The let keyword was introduced in ES6 (2015)


Variables declared with let have Block Scope.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script language=”javascript”>
let x = 5;
let y = 8;
let z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
Output:
JavaScript Variables
In this example, x, y, and z are variables.
The value of z is: 13

Functions in Javascript:
A JavaScript function is a block of code designed to perform a
particular task.

A JavaScript function is executed when "something" invokes it (calls


it).

Simple alert statements using function and how function call works in
java:
<html>
<body>
<script language=”javascript”>
function fun1() {
alert("functions called");
}
</script>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the
result:</p>

<input type="submit" value="click me" onclick="fun1()">

</body>

</html>
Program to input and add two numbers in javascript using
function call alert and document:
<html>
<head>
<script language=”javascript”>
function add()
{
var num1, num2, sum;
num1 =
parseInt(document.getElementById("firstnumber").value);
num2 =
parseInt(document.getElementById("secondnumber").value);
sum=num1+num2;
alert("sum is"+sum);

document.getElementById("answer").value = sum;
}
</script>
</head>
<p>First Number: <input typr="text" id="firstnumber"></p>
<p>Second Number: <input type="text"
id="secondnumber"></p>
<button onclick="add()">Add Them</button>
<p>Sum = <input id="answer"></p>
</body>
</html>

Form validations using Javascript:


Q.Write a program to validate a textbox and provide a message
when it is empty or length is less than 5.
Ans:
<html>
<head>
<script language="javascript">
function validateForm() {
x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
if(x.length < 5) {
alert("name must be greater than 4 character length");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</html>

Javascript Email validation:


function below checks if the content has the general syntax of an
email. This means that the input data must contain an @ sign and
at least one dot (.). Also, the @ must not be the first character of
the email address, and the last dot must be present after the @
sign, and minimum 2 characters before the end:
<html>
<head>
<script language="javascript">
function validateForm()
{
alert("called");
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address"); return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="" " method="post"> Email:
<input type="text" name="email">
<input type="submit" value="Submit" onclick="return
validateForm();" > </form> </body> </html>
Java JavaScript

Java is a strongly typed


language and variables must
JavaScript is a loosely typed
be declared first to use in the
language and has a more
program. In Java, the type of
relaxed syntax and rules.
a variable is checked at
compile-time.

Java is an object-oriented
JavaScript is a scripting
programming language
language used for creating
primarily used for developing
interactive and dynamic web
complex enterprise
pages.
applications.

JavaScript code used to run


Java applications can run in
only in the browser, but now
any virtual machine(JVM) or
it can run on the server via
browser.
Node.js.

Objects of Java are class-


based even we can’t make JavaScript Objects are
any program in java without prototype-based.
creating a class.

JavaScript file has the file


Java program has the file
extension “.js” and it is
extension “.Java” and
interpreted but not compiled,
translates source code into
every browser has the
bytecodes which are
Javascript interpreter to
executed by JVM(Java
execute JS code.if compile
Virtual Machine).
time
Form get vs post method differences:

In GET method we can not


send large amount of data
In POST method large
rather limited data of some
amount of data can be sent
number of characters is sent
because the request
because the request
parameter is appended into
parameter is appended into
the body.
the URL.

GET request is POST request is


comparatively less secure comparatively more secure
because the data is exposed because the data is not
in the URL bar. exposed in the URL bar.

Request made through GET Request made through


method are stored in POST method is not stored
Browser history. in Browser history.

GET method request can be POST method request can


saved as bookmark in not be saved as bookmark in
browser. browser.
Javascript operators:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators

Arithmatic opeartor
Operato Description
r

+ Addition

- Subtraction

* Multiplication

** Exponentiation (ES2016)

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement
Comparison Operators:
Operato Description
r

== equal to

!= not equal

> greater than

< less than

>= greater than or equal to

<= less than or equal to


Creating an Array in javascript:
Using an array literal is the easiest way to create a JavaScript
Array.
Syntax:
const array_name = [item1, item2, ...];
It is a common practice to declare arrays with
the const keyword.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

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

<script language=”javascript”>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>
Output:
JavaScript Arrays
Saab,Volvo,BMW
Loops in javascript:

JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 for/of - loops through the values of an iterable object
 while - loops through a block of code while a specified condition is
true
 do/while - also loops through a block of code while a specified
condition is true

Example to find table of number using for loops:


<html>
<script language="javascript">
function table()
{
var p,q,i;
p=parseInt(document.getElementById("num").value);
for(i=1;i<=10;i++)
{
q=p*i;
document.writeln(q);
}
}

</script>
<body>
<h1>Generate Table</h1>
Enter any number<input type="text" id="num">
<input type="text" id="a">
<input type="submit" onclick="table()">
</body>
</html>
Output:
Enter any number 5
5 10 15 20 25 30 35
Conditional Statements

Very often when you write code, you want to perform different
actions for different decisions.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified


condition is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use switch to specify many alternative blocks of code to be
executed

If else program already discussed in validations


HTML Events:

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


user does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

 Common HTML Events


 Here is a list of some common HTML events:

Event Description

Onchange An HTML element has been changed

Onclick The user clicks an HTML element

Onmouseover The user moves the mouse over an HTML element

Onmouseout The user moves the mouse away from an HTML element

Onkeydown The user pushes a keyboard key

Onload The browser has finished loading the page


AJAX:
AJAX, or Asynchronous JavaScript and XML, is a set of web
development technologies that allow web applications to be
more responsive and interactive:
What ajax can do:
AJAX is a developer's 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
 Advantages of AJAX: Improved user experience
AJAX allows for partial page updates instead of full page reloads,
which creates a more responsive feel for users.
Reduced server load
AJAX reduces the amount of data transferred by only exchanging
specific data with the server, which leads to faster loading times
and reduced server strain.
Better form validation
AJAX can be used for client-side form validation, providing
immediate feedback to users without requiring a form
submission request.
Dynamic content updates
AJAX enables real-time data updates without full page reloads,
which is ideal for features like live chat, stock tickers, or
collaborative editing.
Speed
AJAX provides a quicker, better search experience for users since
only essential data is sent to the browser.
AJAX allows web pages to be updated asynchronously by
exchanging data with a web server behind the scenes. This means
that it is possible to update parts of a web page, without reloading
the whole page.

How AJAX Works

 1. An event occurs in a web page (the page is loaded, a button is


clicked)
 2. An XMLHttpRequest object is created by JavaScript
 3. The XMLHttpRequest object sends a request to a web server
 4. The server processes the request
 5. The server sends a response back to the web page
 6. The response is read by JavaScript
 7. Proper action (like page update) is performed by JavaScript

XMLHTTPRequest object:

XMLHTTPRequest object is an API which is used for fetching data


from the server. XMLHTTPRequest is basically used in Ajax
programming. It retrieve any type of data such as json, xml, text etc.
It request for data in background and update the page without
reloading page on client side. An object of XMLHTTPRequest is
used for asynchronous communication between client and server.

Properties of XMLHttpRequest Object:

 onload: When the request is received (loaded), it defines a


function to be called.
 onreadystatechange: A function will be called whenever the
readyState property changes.
 readyState: It defines the current state of the request or holds the
current status of the XMLHttpRequest. There are five states of a
request:
o readyState= 0: It represents the Request not initialized.
o readyState= 1: Establishment of server connection.
o readyState= 2: Request has been received
o readyState= 3: During the time of processing the request
o readyState= 4: Response is ready after finishing the request
Simple AJAX program:
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change
Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.htm", true);
xhttp.send();
}
</script>
</body>
</html>

ajax_info.htm
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web
page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

You might also like