You are on page 1of 88

Advanced Web Development

subject code:202046701
Unit-1

Prepared By:Prof.Khushali Patel


Assistant Professor (IT)
A D Patel Institute of Technology
Teaching & Examination Scheme:
Unit-1
Basic Syntax of CSS
 A CSS rule has two main parts: a selector, and one or more
declarations

h1 {color:blue; font-size: 12px;}

 The selector can be HTML element, id or class.


 Each declaration consists of a property and a value.
 The property is the style attribute you want to change. Each
property has a value.

4
The “id” selector
 The id selector is used to specify a style for a single, unique element.
 The id selector uses the id attribute of the HTML element, and is defined with a
"#“ in css.
 The style rule below will be applied to the element with id="para1":

HTML CSS
<h1 id=“para1”> #para1{
Hello Friends color: blue;
</h1> }

<h1> Output
How are you Hello Friends
</h1> How are you
The “class” selector
 The class selector is used to specify a style for a group of elements.
 The class selector uses the HTML class attribute, and is defined with a ".“ in
css.

HTML CSS
<h1 class=“myClass”> .myClass{
Hello Friends color: blue;
</h1> }
<h1>
How are you
</h1> Output
<h1 class=“myClass”> Hello Friends
How are you How are you
</h1> How are you
Different ways to write CSS

 There are three ways of writing a style sheet:


1. Inline Style
2. Internal/Embedded Style sheet
3. External Style Sheet
1) Inline Style

 It is possible to place CSS right in your HTML code, and this method of CSS
usage is referred to as inline css.
 Inline CSS has the highest priority out of external, internal, and inline CSS.
 This means that you can override styles that are defined in external or
internal by using inline CSS.
 If you want to add a style inside an HTML element all you have to do is specify
the desired CSS properties with the style HTML attribute.
 Example:

HTML
<p style="background: blue; color: white;"> My Inline CSS </p>
2) Internal Style Sheet
 This type of CSS is only for Single Web Page.
 When using internal CSS, we must add a new tag, <style>, inside the <head>
tag.
 The HTML code below contains an example of <style>'s usage.

HTML
<html><head>
<style type="text/css">
p{ color: red;}
</style>
</head><body>
<p>Your page's content!</p></body>
</html>
3) External Style Sheet

 When using CSS it is preferable to keep the CSS separate from your HTML.
 Placing CSS in a separate file allows the web designer to completely
differentiate between content (HTML) and design (CSS).
 External CSS is a file that contains only CSS code and is saved with a ".css"
file extension.
 This CSS file is then referenced in your HTML using the <link> instead of
<style>.
3) External Style Sheet (Cont.)

 Example :

Demo.html test.css
<html> #para1{
<head> text-align: center;
<link rel=“stylesheet” }
type=“text/css” href=“test.css”> p
</head> {
<body> color : blue;
}
<p> Hello Friends </p>
<p id=“para1”> How are you? </p> Output
Hello Friends
</body> How are you?
</html>
3) External Style Sheet (Cont.)

 Advantages:
 It keeps your website design and content separate.
 It's much easier to reuse your CSS code if you have it in a separate file. Instead of
typing the same CSS code on every web page you have, simply have many pages
refer to a single CSS file with the "link" tag.
 You can make drastic changes to your web pages with just a few changes in a single
CSS file.
Assign Multiple Classes
 We can apply different class to same html element by giving space separated
class names in the class attribute:

Demo.html test.css
<html> . class1
<head> {
<link rel=“stylesheet” color : blue;
type=“text/css” href=“test.css”> }
</head> . class2
<body> {
text-align : center;
<h1 class=“class1 class2”> }
How are you?
</h1> Output

</body>
How are you?
</html>
Multiple Selection
 We can apply same css to multiple selectors using comma separated selector
list, for example :

Demo.html test.css
<html> p, h1
<head> {
<link rel=“stylesheet” color : blue;
type=“text/css” href=“test.css”> }
</head>
<body>

<p> Hello Friends </p>


<h1> How are you? </h1> Output
Hello Friends
</body>
</html>
How are you?
Multi-level Selection
 We can use hierarchical path to target html element by space separated
element/class/id names, for example :

Demo.html test.css
<html> div h1
<head> {
<link rel=“stylesheet” color : blue;
type=“text/css” href=“test.css”> }
</head>
<body>
<h1>Hello Friends…</h1>
<div>
<h1>How are you?</h1> Output
</div> Hello Friends…
</body>
How are you?
</html>
What is Responsive Web Design?
 Responsive web design makes your web page look good on all
devices.
 Responsive web design uses only HTML and CSS.
 Responsive web design is not a program or a JavaScript.
 Web pages can be viewed using many different devices:
desktops, tablets, and phones. Your web page should look
good, and be easy to use, regardless of the device.
 Web pages should not leave out information to fit smaller
devices, but rather adapt its content to fit any device:
Responsive Web Design - The Viewport
 The viewport is the user's visible area of a web page.
 The viewport varies with the device, and will be smaller on a mobile
phone than on a computer screen.
 <meta name="viewport" content="width=device-width, initial-
scale=1.0">
 This gives the browser instructions on how to control the page's
dimensions and scaling.
 The width=device-width part sets the width of the page to follow the
screen-width of the device (which will vary depending on the device).
 The initial-scale=1.0 part sets the initial zoom level when the page is
first loaded by the browser.
Size Content to The Viewport
 Users are used to scroll websites vertically on both desktop and mobile
devices - but not horizontally!
 So, if the user is forced to scroll horizontally, or zoom out, to see the
whole web page it results in a poor user experience.
 Some additional rules to follow:
 1. Do NOT use large fixed width elements - For example, if an image
is displayed at a width wider than the viewport it can cause the viewport
to scroll horizontally. Remember to adjust this content to fit within the
width of the viewport.
 2. Do NOT let the content rely on a particular viewport width to
render well - Since screen dimensions and width in CSS pixels vary
widely between devices, content should not rely on a particular viewport
width to render well.
 3. Use CSS media queries to apply different styling for small and
large screens - Setting large absolute CSS widths for page elements will
cause the element to be too wide for the viewport on a smaller device.
Instead, consider using relative width values, such as width: 100%. Also,
be careful of using large absolute positioning values. It may cause the
element to fall outside the viewport on small devices.
Responsive Web Design - Grid-View
 Many web pages are based on a grid-view, which means that the
page is divided into columns:
 A responsive grid-view often has 12 columns, and has a total width of
100%, and will shrink and expand as you resize the browser window.
Building a Responsive Grid-View
 First ensure that all HTML elements have the box-sizing property set to
border-box. This makes sure that the padding and border are included in the
total width and height of the elements.
 Add the following code in your CSS:
*{
box-sizing: border-box;
}
Responsive Web Design - Images
 Using The width Property
 If the width property is set to a percentage and the height property is set to
"auto", the image will be responsive and scale up and down:
img {
width: 100%;
height: auto;
}
If the max-width property is set to 100%, the image will scale down if it has to, but
never scale up to be larger than its original size:

img {
max-width: 100%;
height: auto;
}
Background Images
 Background images can also respond to resizing and scaling.
 Here we will show three different methods:
1. If the background-size property is set to "contain", the background image
will scale, and try to fit the content area. However, the image will keep its
aspect ratio (the proportional relationship between the image's width and
height):
div {
width: 100%;
height: 400px;
background-image: url('img_flowers.jpg');
background-repeat: no-repeat;
background-size: contain;
border: 1px solid red;
}
 2. If the background-size property is set to "100% 100%", the background
image will stretch to cover the entire content area:
 div {
width: 100%;
height: 400px;
background-image: url('img_flowers.jpg');
background-size: 100% 100%;
border: 1px solid red;
}
 3. If the background-size property is set to "cover", the background image
will scale to cover the entire content area. Notice that the "cover" value
keeps the aspect ratio, and some part of the background image may be
clipped:
 div {
width: 100%;
height: 400px;
background-image: url('img_flowers.jpg');
background-size: cover;
border: 1px solid red;
}
CSS Grid
The CSS Grid Layout Module offers a grid-based layout system, with
rows and columns, making it easier to design web pages without having
to use floats and positioning.
Grid Elements

 A grid layout consists of a parent element, with one or more child


elements.
 <div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
</div>
Display Property
 An HTML element becomes a grid container when its display property is set to
grid or inline-grid.
 All direct children of the grid container automatically become grid
items.
Grid Columns Grid Rows
The vertical lines of grid The horizontal lines of grid items are
items are called columns. called rows.
adjust the gap size by using one of the following properties:
 column-gap
 row-gap
 Gap

.grid-container {
display: grid;
column-gap: 50px;
}

.grid-container {
display: grid;
row-gap: 50px;
}
All CSS Grid Properties
Property Description
column-gap Specifies the gap between the columns
gap A shorthand property for the row-gap and the column-gap properties

grid A shorthand property for the grid-template-rows, grid-template-columns, grid-template-


areas, grid-auto-rows, grid-auto-columns, and the grid-auto-flow properties
grid-area Either specifies a name for the grid item, or this property is a shorthand property for
the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
grid-auto-columns Specifies a default column size
grid-auto-flow Specifies how auto-placed items are inserted in the grid
grid-auto-rows Specifies a default row size
grid-column A shorthand property for the grid-column-start and the grid-column-end properties

grid-column-end Specifies where to end the grid item


grid-column-gap Specifies the size of the gap between columns
grid-column-start Specifies where to start the grid item
grid-gap A shorthand property for the grid-row-gap and grid-column-gap properties

grid-row A shorthand property for the grid-row-start and the grid-row-end properties

grid-row-end Specifies where to end the grid item


grid-row-gap Specifies the size of the gap between rows
grid-row-start Specifies where to start the grid item
grid-template A shorthand property for the grid-template-rows, grid-template-columns and grid-
areas properties
grid-template-areas Specifies how to display columns and rows, using named grid items

grid-template-columns Specifies the size of the columns, and how many columns in a grid layout
CSS Framework
 many free CSS Frameworks that offer Responsive Design.
 Using W3.CSS
 A great way to create a responsive design, is to use a responsive style sheet,
like W3.CSS
 W3.CSS makes it easy to develop sites that look nice at any size!

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
Bootstrap
 Another popular framework is Bootstrap. It uses HTML and CSS to make
responsive web pages:
 <!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css
/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js
/bootstrap.bundle.min.js"></script>
</head>
<body>
JavaScript Introduction
 JavaScript Can Change HTML Content
document.getElementById("demo").innerHTML = "Hello JavaScript";
 JavaScript Can Change HTML Styles
document.getElementById("demo").style.fontSize = "35px";
 JavaScript Can Hide HTML Elements
document.getElementById("demo").style.display = "none";
 JavaScript Can Show HTML Elements
document.getElementById("demo").style.display = "block";
<script> tag
 The <script> tag is used to define a client-side script (JavaScript).
 The <script> element either contains scripting statements, or it points to an
external script file through the src attribute.
 Example :

Internal javascript Code External javascript Code


<html> <html>
<head> <head>
<title>HTML script Tag</title> <title>HTML script Tag</title>
</head> </head>
<body> <body>
<script type="text/javascript"> <script src=“PathTo.JS”>
// Java Script Code Here </script>
</script> </body>
</body> </html>
</html>
JavaScript Output

 Writing into an HTML element, using innerHTML.


<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
 Writing into the HTML output using document.write().
<script>
document.write(5 + 6);
</script>
Using document.write() after an HTML document is loaded, will delete all existing HTML:
 Writing into an alert box, using window.alert()
<script>
window.alert(5 + 6);
</script>
 Writing into the browser console, using console.log()
<script>
console.log(5 + 6);
</script>
JavaScript Objects
 An object is just a special kind of data, with properties and methods.
 Accessing Object Properties
 Properties are the values associated with an object.
 The syntax for accessing the property of an object is below
objectName.propertyName
 This example uses the length property of the Javascript’s inbuilt
object(String) to find the length of a string:
var message="Hello World!";
var x=message.length;
JavaScript Objects (Cont.)
 Accessing Object Methods
 Methods are the actions that can be performed on objects.
 You can call a method with the following syntax.
objectName.methodName()
 This example uses the toUpperCase method of the String
object to convert string to upper case:
var message="Hello World!";
var x=message.toUpperCase();
JavaScript’s inbuilt Objects

 JavaScript comes with some inbuilt objects which are,


 String
 Date
 Array
 Boolean
 Math
 RegExp
etc….
Math Object in JavaScript

 The Math object allows you to perform mathematical tasks.


 The Math object includes several mathematical constants and methods.
 Example for using properties/methods of Math:

Code
<script>
var x=Math.PI;
var y=Math.sqrt(16);
</script>
Math Object (Cont.)
 Math object has some properties which are,

Properties Description
E Returns Euler's number(approx.2.718)
LN2 Returns the natural logarithm of 2 (approx.0.693)
LN10 Returns the natural logarithm of 10 (approx.2.302)
LOG2E Returns the base-2 logarithm of E (approx.1.442)
LOG10E Returns the base-10 logarithm of E (approx.0.434)
PI Returns PI(approx.3.14)
SQRT1_2 Returns square root of ½
SQRT2 Returns square root of 2
Math Methods (Cont.) Method Description
Method Description exp(x) Returns the value of Ex
abs(x) Returns the absolute value of x ceil(x) Returns x, rounded
upwards to the nearest
sin(x) Returns the sine of x (x is in integer
radians)
floor(x) Returns x, rounded
cos(x) Returns the cosine of x (x is in downwards to the nearest
radians) integer
tan(x) Returns the tan of x (x is in log(x) Returns the natural
radians) logarithm(base E) of x
acos(x) Returns the arccosine of x, in round(x Rounds x to the nearest
radians ) integer
asin(x) Returns the arcsine of x, in pow(x, Returns the value of x to
radians y) the power of y
atan(x) Returns the arctangent of x as max(x, Returns the number with
a numeric value y,z,..., the highest value
atan2(x) Returns arctangent of x n)
random(x Returns random floating sqrt(x) Returns the square root of
) number between 0 to 1 x
JavaScript Date Objects

Creating Date Objects


Date objects are created with the new Date() constructor.
There are 9 ways to create a new date object:
new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)
new Date(milliseconds)
JavaScript Date Methods
Methods Description
getDate() It returns the integer value between 1
and 31 that represents the day for the
specified date on the basis of local time.
getDay() It returns the integer value between 0
and 6 that represents the day of the
week on the basis of local time.
getFullYears() It returns the integer value that
represents the year on the basis of local
time.
getHours() It returns the integer value between 0
and 23 that represents the hours on the
basis of local time.
getMilliseconds() It returns the integer value between 0
and 999 that represents the milliseconds
on the basis of local time.
getMinutes() It returns the integer value between 0
and 59 that represents the minutes on
the basis of local time.
JavaScript Date Methods
getMonth() It returns the integer value between 0 and 11 that
represents the month on the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that


represents the seconds on the basis of local time.

getUTCDate() It returns the integer value between 1 and 31 that


represents the day for the specified date on the basis of
universal time.

getUTCDay() It returns the integer value between 0 and 6 that


represents the day of the week on the basis of universal
time.

getUTCFullYears() It returns the integer value that represents the year on


the basis of universal time.

getUTCHours() It returns the integer value between 0 and 23 that


represents the hours on the basis of universal time.

getUTCMinutes() It returns the integer value between 0 and 59 that


represents the minutes on the basis of universal time.

getUTCMonth() It returns the integer value between 0 and 11 that


represents the month on the basis of universal time.
setDate() It sets the day value for the specified date on the basis
of local time.
setDay() It sets the particular day of the week on the basis of
local time.
setFullYears() It sets the year value for the specified date on the
basis of local time.
setHours() It sets the hour value for the specified date on the
basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on
the basis of local time.
setMinutes() It sets the minute value for the specified date on the
basis of local time.
setMonth() It sets the month value for the specified date on the
basis of local time.
setSeconds() It sets the second value for the specified date on the
basis of local time.
setUTCDate() It sets the day value for the specified date on the basis
of universal time.
setUTCDay() It sets the particular day of the week on the basis of
universal time.
setUTCFullYears() It sets the year value for the specified date on the
basis of universal time.
setUTCHours() It sets the hour value for the specified date on the
basis of universal time.
setUTCMilliseconds() It sets the millisecond value for the specified
date on the basis of universal time.

setUTCMinutes() It sets the minute value for the specified date


on the basis of universal time.
setUTCMonth() It sets the month value for the specified date
on the basis of universal time.
setUTCSeconds() It sets the second value for the specified date
on the basis of universal time.
toDateString() It returns the date portion of a Date object.
toISOString() It returns the date in the form ISO format
string.
toJSON() It returns a string representing the Date object.
It also serializes the Date object during JSON
serialization.
toString() It returns the date in the form of string.
toTimeString() It returns the time portion of a Date object.
toUTCString() It converts the specified date in the form of
string using UTC time zone.
valueOf() It returns the primitive value of a Date object.
JavaScript Date Example

Current Date and Time: <span id="txt"></span>


<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>
Output:

Current Date and Time: Fri Aug 11 2023 09:38:34 GMT+0530 (India Standard
Time)
JavaScript Date Example

<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>

Output:

Date is: 11/8/2023


JavaScript Objects

 A javaScript object is an entity having state and behavior (properties and


method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
 JavaScript is an object-based language. Everything is an object in JavaScript.
 JavaScript is template based not class based. Here, we don't create class to
get the object. But, we direct create objects.
 Creating Objects in JavaScript
There are 3 ways to create objects.
 By object literal
 By creating instance of Object directly (using new keyword)
 By using an object constructor (using new keyword)
JavaScript Object by object literal
 However, it is also possible to assign values when it is made with literal
values.

example
<script>
person={
firstname: “ADIT",
lastname: "College",
age: 50,
eyecolor: "blue"
}
alert(person.firstname + " is " + person.age + " years old.");
</script>
By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
 Here, new keyword is used to create object.
 example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output
101 Harsh 50000
By using an Object constructor
 A constructor is pre defined method that will initialize your object.
 To do this in JavaScript a function is used that is invoked through the new
operator.
 Any properties inside the newly created object are assigned using this
keyword, referring to the current object being created.

example
<script>
function person(firstname, lastname, age){
this.firstname = firstname;
this.lastname = lastname;
this. changeFirstName = function (name){ this.firstname =
name };
}
var person1=new person("Narendra","Modi",50);
person1.changeFirstName(“NAMO”);
alert(person1.firstname + “ ”+ person1.lastname);
</script>
JavaScript Object Methods
Object.assign() This method is used to copy
enumerable and own properties from
a source object to a target object
Object.create() This method is used to create a new
object with the specified prototype
object and properties.
Object.defineProperty() This method is used to describe
some behavioral attributes of the
property.
Object.defineProperties() This method is used to create or
configure multiple object properties.
Object.entries() This method returns an array with
arrays of the key, value pairs.
JavaScript Object Methods
Object.freeze() This method prevents existing
properties from being removed.
Object.getOwnPropertyDescriptor() This method returns a property
descriptor for the specified property of
the specified object.
Object.getOwnPropertyDescriptors() This method returns all own property
descriptors of a given object.

Object.getOwnPropertyNames() This method returns an array of all


properties (enumerable or not) found.

Object.getOwnPropertySymbols() This method returns an array of all


own symbol key properties.
Object.getPrototypeOf() This method returns the prototype of
the specified object.
JavaScript Object Methods
Object.is() This method determines whether two
values are the same value.
Object.isExtensible() This method determines if an object is
extensible
Object.isFrozen() This method determines if an object was
frozen.
Object.isSealed() This method determines if an object is
sealed.
Object.keys() This method returns an array of a given
object's own property names.
Object.preventExtensions() This method is used to prevent any
extensions of an object.
Object.seal() This method prevents new properties from
being added and marks all existing
properties as non-configurable.
Object.setPrototypeOf() This method sets the prototype of a
specified object to another object.
Object.values() This method returns an array of values.
Document Object Model (DOM)

 The Document Object Model is a platform and language neutral interface that
will allow programs and scripts to dynamically access and update the content,
structure and style of documents.
 The window object is the primary point from which most other objects come.
 From the current window object access and control can be given to most
aspects of the browser features and the HTML document.
 When we write :
document.write(“Hello World”);
 We are actually writing :
window.document.write(“Hello World”);
The window is just there by default
DOM (Cont)
 This window object represents the window or frame that displays the
document and is the global object in client side programming for JavaScript.
 All the client side objects are connected to the window object.

window

self, frames[] navigator location history document screen


parent,
window,
top
Document Object Properties
Property Description
anchors Returns a collection of all the anchors in the document
applets Returns a collection of all the applets in the document
body Returns the body element of the document
cookie Returns all name/value pairs of cookies in the document
Returns the domain name of the server that loaded the
domain document
forms Returns a collection of all the forms in the document
images Retuns a collection of all the images in the document
links Returns a collection of all the links in the document (CSSs)
Returns the URL of the document that loaded the current
referrer document
title Sets or returns the title of the document
URL Returns the full URL of the document
Document Object Methods
Method Description
write() Writes HTML expressions or JavaScript code
to a document
writeln() Same as write(), but adds a newline
character after each statement
open() Opens an output stream to collect the
output from document.write() or
document.writeln()
close() Closes the output stream previously opened
with document.open()
getElementById() Accesses element with a specified id
getElementsByName() Accesses all elements with a specified name
getElementsByTagNam Accesses all elements with a specified tag
e() name
setTimeout(), Set a time period for calling a function once; or
clearTimeout() cancel it.
getElementById()
 When we suppose to get the reference of the element from HTML in
JavaScript using id specified in the HTML we can use this method.
 Example :
HTML
<html>
<body>
<input type=“text”
id=“myText”>
</body>
</html>

JavaScript
<script>
function myFunction()
{
var txt = document.getElementById(“myText”);
alert(txt.value);
}
</script>
getElementsByName()

 When we suppose to get the reference of the elements from HTML in


JavaScript using name specified in the HTML we can use this method.
 It will return the array of elements with the provided name.
 Example :

HTML JavaScript
<html> <script>
<body> function myFunction()
<input type=“text” {
name=“myText”>
</body> a=document.getElementsByName(“myText”)[
</html> 0];
alert(a.value);
}
</script>
getElementsByTagName()

 When we suppose to get the reference of the elements from HTML in


JavaScript using name of the tag specified in the HTML we can use this
method.
 It will return the array of elements with the provided tag name.
 Example :
HTML JavaScript
<html> <script>
<body> function myFunction() {
<input type=“text”
name=“uname”> a=document.getElementsByTagName(“input
<input type=“text” ”);
name=“pword”> alert(a[0].value);
</body> alert(a[1].value);
</html> }
</script>
AJAX Introduction
 What is AJAX?
 AJAX = Asynchronous JavaScript And XML.

 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)
 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
Continue..
 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

Modern Browsers (Fetch API)


 Modern Browsers can use Fetch API instead of the XMLHttpRequest Object.
 The Fetch API interface allows web browser to make HTTP requests to web
servers.
 If you use the XMLHttpRequest Object, Fetch can do the same in a simpler
way.
AJAX - The XMLHttpRequest Object
 The keystone 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
Example
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, 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


Used for GET requests

send(string) Sends the request to the server.


Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent


XMLHttpRequest Object Properties
Property Description
onload Defines a function to be called when the request is received (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"
For a complete list go to the Http Messages Reference

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


AJAX - XMLHttpRequest

Method Description
open(method, url, Specifies the type of request
async)
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 (used for GET)
send(string) Sends the request to the server (used for POST)
AJAX - Server Response
AJAX XML Example

You might also like