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

WP Notes 2024 Mca

The document provides an overview of web programming concepts, focusing on HTML5, JavaScript, and related technologies. It covers the structure and features of HTML5, including new elements, MIME types, web storage, and web workers, along with examples and explanations of their usage. Additionally, it discusses the evolution of HTML and the advantages of using HTML5 for modern web development.

Uploaded by

kushaldevarlk
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)
19 views591 pages

WP Notes 2024 Mca

The document provides an overview of web programming concepts, focusing on HTML5, JavaScript, and related technologies. It covers the structure and features of HTML5, including new elements, MIME types, web storage, and web workers, along with examples and explanations of their usage. Additionally, it discusses the evolution of HTML and the advantages of using HTML5 for modern web development.

Uploaded by

kushaldevarlk
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/ 591

WEB PROGRAMMING

<!DOCTYPE>

<html>

<body bgcolor=black>

<table border=2 bordercolor=red>

<tr bgcolor=yellow><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>

<tr><td bgcolor=pink>Sonoo</td><td>Jaiswal</td><td>60</td></tr>

<tr><td>James</td><td>William</td><td>80</td></tr>

<tr><td>Swati</td><td>Sironi</td><td bgcolor=red>82</td></tr>

<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
</body>
</html>
Unit I

HTML5 and JavaScript


Hyper Text: HyperText simply means "Text within Text."

A text has a link within it, is a hypertext.

Hypertext refers to the way in which Web pages (HTML


documents) are linked together.

Thus, the link available on a webpage is called


Hypertext.
Markup language:

A markup language is a computer language

that is used to apply layout and formatting conventions to a text


document.

Markup language makes text more interactive and dynamic.

It can turn text into images, tables, links, etc.

Web Page: A web page is a document which is commonly


written in HTML and translated by a web browser.
HTML, developers can create web pages, websites, and similar digital
documents.

HTML is only about structure, not appearance.

Tag - Is a keyword enclosed in <>


<!DOCTYPE>
<html>
<body bgcolor=DodgerBlue>
<table border=2 bordercolor=red>

<tr bgcolor=yellow><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>

<tr><td bgcolor=pink>Sonoo</td><td>Jaiswal</td><td>60</td></tr>

<tr><td>James</td><td>William</td><td>80</td></tr>

<tr><td>Swati</td><td>Sironi</td><td bgcolor=red>82</td></tr>

<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
</body>
</html>
What are Cascading Style Sheets?
styles define how to display HTML elements;
MIME (Multipurpose Internet Mail Extensions)

MIME was defined in 1992 by the Internet Engineering Task Force(IETF).

The MIME tells what is in a message so that the message contents are
arranged or used in proper way.

The MIME protocol allows the users to exchange various types of digital
content such as pictures, audio, video, and various types of documents
and files in the e-mail.

A media type indicates the nature and format of a document, or a file.

Is the name indicates, it is an extension to the Internet email protocol


that allows it’s users to exchange different kinds of data files over the
Internet such as images, audio, and video.
Structure of a MIME type
A MIME type consists of just two parts:

A type and a subtype, separated by a slash (/) — without spaces.


MIME-type is not case-sensitive, but it is commonly written in lower
case.

Main_mime_type/mime_subtype

The type represents the general category into which the data type
video or text. The subtype identifies the exact kind of data of the
specified type the MIME type represents.

For example, for the MIME type text, the subtype might be plain (plain
text),html (HTML source code) files.
Network Virtual Terminal (NVT)

User agent is a small piece of data that is sent by your web browser when accessing a
website or application.

A browser's user agent string (UA) helps identify which browser is being used, what
version, and on which operating system.
Ex:
A GIF image for ex, has the following MIME type:

audio/mp3
text/css
video/mp4
text/html
Some of the commonly used MIME types

MIME Type Type of File extension


application/mp4 MPEG4 files mp4
application/octet-stream Non-interpreted binary files bin
application/msword Word document files doc
application/pdf Adobe Acrobat files pdf
application/rtf Rich Text Format rtf
application/vnd.mspowerpoi Microsoft Powerpoint ppt
nt
application/xml XML files Au,snd
audio/mpeg MPEG audio files Mpg, mp3
image/gif Gif image
image/jpeg Jpeg images Jpg,jpeg
text/css Style Sheet css
text/html HTML files Htm,html
text/plain Unformatted text files Txt,g,h,cc,
hh
There are many sub parts come under MIME headers.

1. MIME-Version

MIME-Version header is used to indicate that the message is MIME formatted. This header
is having a value of “1.0” typically.
eg: MIME-Version: 1.0

2. Content-Type

This header is used to describe the content type of the message. The Content-Type header
includes the type and a sub-type parts.

eg: Content-Type: text/plain

3. Content-Disposition
The original MIME specifications only described the structure of mail messages

There are two types of Content-Disposition:

1) Inline Content-Disposition

2) Attachment Content-Disposition
Inline Content-Disposition

The Inline Content-Disposition would be automatically displayed when the message is


shown.

Attachment Content-Disposition

The Attachment Content-Disposition will not be displayed automatically. It needs the user
action to get opened and displayed.

eg: Content-Disposition: attachment; filename=genome.jpeg;

4. Content-Transfer-Encoding
It indicates whether or not a binary-to-text encoding scheme has been used on top of the
original encoding as specified within the Content-Type header:

1) If such a binary-to-text encoding method has been used, it states which one.

2) If not, it provides a descriptive label for the format of content, with respect to the
presence of 8-bit or binary content.
History of HTML

1991 HTML first published

1995 HTML 2.0


After HTML 4.01 was released, focus shifted
to XHTML standards.
1997 HTML 3.2

1999 HTML 4.01 XHTML 2.0

2000 XHTML 1.0

2002 - HTML5 is much more tolerant and can


2009 XHTML 2.0 handle markup from all the prior versions.

Though HTML5 was published officially in 2012, it


2012 HTML5
has been in development since 2004.
Why use HTML5

HTML5 is a next version of HTML.

It is enriched with advance features which makes it easy and


interactive for designer/developer and users.

It allows you to play a video and audio file.


New Elements in HTML5

<article> <figcaption> <progress>


<aside> <footer> <section>
<audio> <header> <source>
<canvas> <hgroup> <svg>
<datalist> <mark> <time>
<figure> <nav> <video>
Other New Features in HTML5

◼ Built-in audio and video support (without plugins).


◼ Enhanced form controls and attributes.
◼ The Canvas (a way to draw directly on a web page)
◼ Drag and Drop functionality.
◼ Support for CSS3 (the newer and more powerful version
of CSS)
◼ More advanced features for web developers, such as
data storage and offline applications.
First Look at HTML5
The DOCTYPE declaration from XHTML?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

In HTML5, there is just one possible DOCTYPE declaration and it is simpler:

<!DOCTYPE html>

The DOCTYPE tells the browser which type and version of document .
The <html> Element

<html> element in XHTML:


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">

Again, HTML5 simplifies this line:

<html lang="en">

The lang attribute in the <html> element declares which language the page
content is in.

Each of the world’s major languages has a two-character code, e.g. Spanish = "es", French =
"fr", German = "de", Chinese = "zh", Arabic = "ar".
HTML 5 Example
HTML 5 Tags

There is a list of newly included tags in HTML 5.

These HTML 5 tags (elements)

1. <audio>It is used to play audio file in HTML.

2. <video>It is used to play video file in HTML.

3. The <article> tag specifies independent, self-contained content in a


Document.
4. That may be a blog, a magazine or a newspaper article.

Forum post
Blog post
News story

An article should have its own meaning and be easily differentiated


from the rest of the web page content
<!DOCTYPE html>
<html>

<head>
<style>
article {
width: 300px;
border: 2px solid gray;
padding: 10px;
border-radius: 10px;
margin: 0 auto;
}

h1 {
color: green;
}
</style>
</head>

<body>
<article>
<img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"
alt="" width="300" height="250" class="alignnone size-medium wp-image-560930" />

<h1>GeeksforGeeks</h1>

<p> Mozilla Firefox is an open-source web browser developed by Mozilla.


Firefox has been the second most popular web browser since January, 2018
</p>

</article>
</body>

</html>
Syntax
The <article> tag comes in pairs.

The content is written between the opening (<article>) and closing (</article>)
tags.
<canvas> It is used to draw canvas.

The HTML <canvas> element is used to draw graphics on


a web page via JavaScript.

Canvas has several methods for drawing paths, boxes, circles, text,
and adding images.

Canvas Examples

A canvas is a rectangular area on an HTML page. By default, a canvas has no border

and no content.

<canvas id="myCanvas" width="200" height="100"></canvas>

To add a border, use the style attribute.


You can access a <canvas> element with the HTML DOM method
getElementById().

The getContext() method returns an object with tools (methods) for


drawing.
Draw the Path - stroke()
The <audio> tag is used to embed sound content in a document,
such as music or other audio streams

<audio controls>

<source src="house.mp4" type="audio/mp4">


<source src="house.mp3" type="audio/mpeg"> Your
browser does not support the audio tag.
</audio>
Inside a <button> element you can put text (and tags like
<i>, <b>, <strong>, <br>, <img>, etc.).
It defines a footer for a section.
<footer>

<header> It defines a header for a section.

HTML Footer Tag

HTML <footer> tag is used to define a footer for a document or a


section.

It is generally used in the last of the section (bottom of the


page).
HTML <header> tag is used

Generally a <header> element contains one or more heading


elements, logo or icons or author's information.

You can use several <header> elements in one document, but a


<header> element cannot be placed within a <footer>,
<address> or another <header> element.
HTML5 Form Input Types and Attributes
HTML5 introduced some new Input Types and Attributes, which makes this
element more dynamic.

1. Input Type “number”

The default type of an input element is text.

Every browser understands this element even when we declare the element
using just the tag.

HTML5 has introduced the type number, specifically to accept numerical


values.

At first sight, it looks like an ordinary text box.

However, when we set focus on the input box (or hover over the box), you will
see that it is a spinner.
check if it allows us to enter non-numerical
values, such as alphabets.
Definition and Usage placeholder

The placeholder attribute specifies a short hint that


describes the expected value of an input field (e.g. a
sample value or a short description of the expected
format).

The short hint is displayed in the input field before the


user enters a value.

Note: The placeholder attribute works with the following


input types: text, search, url, email, and password.
HTML <nav> tag is used to represent a section which contains navigation links,
either within current document or to another document
HTML Web Storage

The Web Storage is one of the great features of HTML5.

Before HTML5 , application data had to be stored in cookies.

Web storage is more secure, large amount of data can be stored


locally. Without affecting performance.

With the Web Storage feature, web applications can locally store
data within the browser on the client or user side.

Also called as DOM storage.

It stores data in the form of key/value pair on the browser.


Storing data with the help of web storage is similar to cookies, but it
is better and faster than cookies storage.

In compared to cookies Web Storage has Following Advantages:

Web Storage can use storage space upto 5MB.

It will not send data to the server side, hence it is faster than cookies
storage.

The data stored by local Storage never expires, but cookies data
expires after some time or session.

Web Storage is more secure than cookies.


Before HTML5, application data had to be stored in cookies, included in
every server request.

Cookies are limited in size.

Web storage is more secure, and large amounts of data can be stored
locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at most 5MB)

Cookies can store upto 4kb data in string type, whereas HTML5 web
storage can store 5mb, (Upto 10mb in some browsers) data in key-
value pair.
Types of Web Storage
1. HTML5 Local Storage

2. HTML 5 Session Storage

The data will not be deleted when the browser is closed, and will be available
the next day, week, or year.

You will put the data and it will still be there when you close the browser.

Session storage will lose the data as soon as you will close the browser. As
the session is going to end.

The session Storage object is equal to the local Storage object, except that it
stores the data for only one session. The data is deleted when the user
closes the specific browser tab.

stores data for one session (data is lost when the browser tab is closed)
Local Storage: Local Storages uses Windows.localStaorage object
which stores data and available for every page.

But data persist even if the browser is closed and reopened


(Stores data with no Expiration).

Session Storage: Session Storage uses Windows.sessionStorage


object which stores data for one session and data will be lost if the
window or browser tab will be closed.
Add Local Storage

To add local storage, localstorage.setItem() method is used with two


parameters.

First parameter is name, and second is value. We can also add local storage
using localstorage.key=value;
object
property
This is nothing but the Session storage once this browser is
closed the session is expired.

There is a expiry date.


HTML Web Workers
A web worker is a JavaScript running in the background, without affecting the
performance of the page.

The Web Workers are the separate JavaScript code which runs in the
background of the web page without affecting the user Interface.

What is Web Worker?

Everyone wants a website or application which work fast and can execute
multiple operations simultaneously without affecting the performance of the
page.

However, sometimes we experience some delay response or degraded


performance of page while executing some large operations.

When executing scripts in an HTML page, the page becomes unresponsive until
the script is finished.

So this problem can be solved using the Web Workers.


Web worker is a separate javascript thread that allows you to
execute multiple threads of Javascript in parallel with each
other.
What is a Web Worker?

When executing scripts in an HTML page, the page


becomes unresponsive until the script is finished

•Web-workers are threaded JavaScript..

•Web-workers requires more space and CPU time.

•Web-workers enhances the speed of a website.

•Web-worker executes codes on the client side (not server-side).

•Web worker threads communicate with each other using postMessage() callback
method
Web Workers are the multithreaded object which can
execute multiple JavaScript in parallel without affecting the
performance of the application or webpage.

A web worker is a JavaScript that runs in the background,


independently of other scripts, without affecting the
performance of the page.

You can continue to do whatever you want: clicking,


selecting things, etc.,
while the web worker runs in the background.
1. Creation of Web worker file:

To create a Web Worker file we need to create an external JavaScript file.

And saved it with the name "worker.js".


2. Creating the Web Worker Object:

In "worker.js" file, we have created the JS file


for web Worker now it needs to call on an
HTML file.

To create the web worker object, you need to call the


Worker() constructor.

syntax to call and create the object of Web Worker:

var worker= new Worker('worker.js');


3. Sending messages between the Worker thread and main thread:

All the communication of Worker thread depends on the

1. postMessage() method :To send a message to a worker


postMessage() of the worker object is used.

2. onmessage - it’s a property: uses event handler to retrieve the


information from the web worker.

4. Terminating the Web Worker:

If you want to immediately terminate the currently running worker in


the main thread, by calling the terminate() method of Web
Worker.

worker.terminate();
HTML Drag and Drop (DnD) is a feature of HTML5.
What to Drag → draggable="true“

ondragstart attribute + function -> drag(event)+ setData()

Where to Drop

ondragover event-> draggable selection is dragged over a target.

event.preventDefault() method

Do the Drop

ondrop attribute calls a function, drop(event) :→when a selection is


being dragged.
To make an element draggable, set the draggable attribute to true:

What to Drag – ondragstart attribute and


setData()
the ondragstart attribute calls a function, drag(event), that specifies what data to
be dragged.

the data type is "text" and the value is the id of the draggable element ("drag1").
Where to Drop – ondragover event
The ondragover event specifies where the dragged data can be
dropped.

The ondragover event occurs when a draggable selection is dragged


over a target.

By default, data/elements cannot be dropped in other elements.

To allow a drop, we must prevent the default handling of the


element.

This is done by calling the event.preventDefault() method for the


ondragover event:
Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.

ondrop attribute calls a function, drop(event):


ondragstart Event

Fires when the user starts dragging of the object.

Ex:
<p draggable="true“ ondragstart="Function1(event)">Drag!</p>

ondrop Event
The ondrop event occurs when a draggable selection is dropped on
a target.

The ondrag event occurs when a selection is being dragged.


data Transfer And Drag Events

You only need to set the draggable attribute to true


(draggable=”true”) on the item you wish to make draggable to its
HTML tag.
ondragover Event
The ondragover event occurs when a draggable selection is
dragged over a target.

ondrag Event

The ondrag event occurs when a selection is being dragged.


Set the data

get the data

Property or attribute
What is a Scripting Language?

The programming languages in which scripts are written are called


scripting

A script or scripting language is a computer language that does not


need the compilation step.

They are interpreted rather than requiring compilation.

In contrast to programming languages that are compiled first


before running, scripting languages do not compile the file and
execute the file without being compiled.
What is Client-Side Scripting?
Client-side scripting refers to the execution of scripts on the client, typically
in a web browser.

client-side script is a tiny program (or collection of instructions) that is put


into a webpage.

This means that the script is run by the client's web browser, and the
resulting HTML is displayed in the browser.

Examples of client-side scripting languages include JavaScript, HTML, and


CSS.

It is handled by the client browser rather than the web server.

Client-side scripting simply means running scripts, such as JavaScript, on


the client device, usually within a browser.
It does not include any interaction with the server, the only
interaction done is receiving the data which was requested.

client-side scripting is a method for browsers to run scripts without


having to connect to a server.

The code runs on the client’s computer’s browser either while the
web page is loading or after it has finished loading.

Client-side scripting is mostly used for dynamic user interface


components including pull-down menus, navigation tools, animation
buttons, and data validation.

The client refers to the script that runs on the user’s computer
system.
The following are the most popular client-side scripting languages:

1.JavaScript is the most commonly used client-side scripting or programming


language.

2.VBScript: This scripting language was developed by Microsoft, based on


Visual Basic.

3.Query: jQuery is a JavaScript library that is fast, tiny, and lightweight. It’s used to
turn a lot of JavaScript code into user-friendly functionality.

4.HTML: Basic and easiest, HTML is used to provide the basic framework for web
designing.

5.CSS: Provides a way to do high dynamic graphic design to make web applications
more attractive and interesting for the end-user.
1. Client-Side Scripting

Client-Side Scripting is an important part of the Dynamic HTML (DHTML). JavaScript

is the main client-side scripting language for the web.

Client-Side scripting is used to make changes in the web page after they arrive at the
browser.

It is useful for making the pages a bit more interesting and user-friendly. It provides

useful gadgets such as calculators, clocks etc.

It enables interaction within a web page.

It is affected by the processing speed of the user's computer.


Client side scripts execute within a user’s browser
and it is used to manage forms and form fields.
The user requests a web page from the server.

The server finds the page and sends it to the user.

The page is displayed on the browser with any scripts running during or after the
display.

Client-Side scripting is used to make web page changes after they arrive at the
browser.

These scripts rely on the user's computer. If the computer is slow, then they
may run slow.

These scripts may not run at all if the browser does not understand the
scripting language.
The client requests a web page from the server.

The script in the page is interpreted by the server, creating or changing the page
content to suit the user (client) and the passing data around.

The page in its final form is sent to the user(client) and then cannot be changed
using Server-Side Scripting.

Server-Side Scripting tends to be used for allowing the users to have individual
accounts and provides data from the databases.

These scripts are never seen by the user.

Server-Side script runs on the server and generate results which are sent to the user.

Running all the scripts puts a lot of load onto a server but not on the user's system.
Server-side scripting refers to the execution of scripts on a server,
which can generate dynamic HTML pages.

This means that the script is run on the server, and the resulting
HTML is sent to the client.

Examples of server-side scripting languages include PHP, Python,


and Ruby.
2. Server-Side Scripting

Server-Side Scripting is used in web development.

The server-side environment runs a scripting language which is called a web server.

Server-Side Scripting is used to provide interactive web sites.

It is different from Client-Side Scripting where the scripts are run by viewing the
web browser, usually in JavaScript.

It is used for allowing the users to have individual accounts and providing data from
databases.

It allows a level of privacy, personalization and provision of information that is very


useful.

It includes ASP.NET and PHP.

It does not rely on the user having specific browser or plug-in.

It is affected by the processing speed of the host server.


This approach is considered more secure than client-side scripting,
as the server handles the execution, enhancing overall security
measures.

Examples of server-side scripting languages include PHP, Java, Ruby,


Python, C#, etc..,
Server-side scripts run on the server instead of the client, often in
order to deliver dynamic content to Webpages in response to user
actions.

Server-side scripts don't have to be written in JavaScript, since the


server may support a variety of languages.
Features

1. Cross Platform Dependency:

•The scripting languages are


independent of the Operating system
they are executing.

•These codes work on all types of OS


without any major modifications.

22. Fast Development:

•The scripting languages are easy


to code, test, and debug and make
any changes faster than other
programming languages.

•Therefore the software


development process takes place
very fast.
3. Easy Integration:

•The scripting language can be easily integrated with other programming


languages like Java, and C++.

4. Versatile:

•Scripting languages are very versatile they can be used for different purposes.

•It can be used for web development, scientific study, administration, and
analysis.

5. Easy to learn:

•One of the major benefits of scripting language is that it is easy to learn when
compared to programming languages.
.
Examples of popular scripting languages: server-side

•PHP: Popular for use on the web. "PHP: Hypertext Preprocessor"

•ASP.net: A web application language that Microsoft developed.

•Node.js: A scripting language you can use on multiple platforms


including Unix, Windows, Mac, and Linux.

•Java: A scripting language used in just about everything, including


consumer Bluetooth devices and applications used by NASA.

•Ruby: A dynamic scripting language that focuses on simplicity.

•Python: A popular language that uses shorter code, making it


easier for beginners to learn
Real-world uses for scripting language
JavaScript Tutorial

JavaScript is used to create client-side dynamic pages.

JavaScript is an object-based scripting language which is lightweight


and cross-platform.

JavaScript is not a compiled language, but it is a translated language.

The JavaScript Translator is responsible for translating the JavaScript


code for the web browser.
Features of JavaScript
All popular web browsers support JavaScript as they provide built-in
execution environments.

JavaScript follows the syntax and structure of the C programming


language.

JavaScript is an object-oriented programming language .

Interpreted language.

It is a case-sensitive language.

It is a case-sensitive language.
Programming logic for interaction with
the user, to handle events, etc.
Behavior
(JAVA SCRIPT)

CSS defines 'rules' or 'styles' for


presenting every aspect of an
PRESENTATION HTML document
(CSS)

CONTENT
(HTML) HTML defines Web sites content through
tags (headings, paragraphs, lists, …)
Java script comment

Single line comment


// comment for single line.
/*
* This is multiple
*Line comment
*/
JavaScript Variable

A JavaScript variable is simply a name of storage location.


A variable defined with the const keyword cannot be reassigned:
JavaScript scope:
Scope determines the accessibility (visibility) of the variables.

Variables defined inside a function are not accessible (visible)


from outside the function.

Local JavaScript Variables

Local variables are created when a function starts, and deleted


when the function is completed.
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.

JavaScript functions are used to perform operations.

We can call JavaScript function many times to reuse the code.

There are mainly two advantages of JavaScript functions.

Code reusability: We can call a function several times so it save coding.

Less coding: It makes our program compact. We don’t need to write many
lines of code each time to perform a common task.
JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a


name, followed by parentheses ().

Function names can contain letters, digits, underscores,


and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas: (parameter1,

parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}


Function Return

When JavaScript reaches a return statement, the function will stop


executing.

If the function was invoked from a statement, JavaScript will "return"


to execute the code after the invoking statement.

Functions often compute a return value.

The return value is "returned" back to the "caller":


JavaScript Objects
A javascript object is an entity having state and behavior (properties and method).
For example: car, bike, chair, glass, keyboard, monitor etc.

In real life, a car is an object.


Objects are variables too. But objects can contain many
values.
What is this?
The this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is


used
JavaScript Array
JavaScript array is an object that represents a collection of
similar type of elements.
Converting an Array to a String

The JavaScript method toString() converts an


array to a string of (comma separated) array
values.
The length Property

The length property of an array returns the length of an


array (the number of array elements).
new keyword is used to create instance of array
JavaScript array constructor (new keyword)
JavaScript Array Methods

Popping items out of an array, or pushing items into an array.


In JavaScript, hoisting allows you to use functions and
variables before they're declared.

In JavaScript, Hoisting is a kind of default behavior in which all


the declarations either variable declaration or function
declaration are moved at the top of the scope just before
executing the program's code
In JavaScript, a variable can be declared
after it has been used.

In simple words, we can say that we can use the


variables and functions in JavaScript before
declaring them.

because JavaScript compiler moves the


declarations of all the variables and functions at
the top of their scope so that there will not be an
error of any kind.
NOTE:

Hoisting is only possible with declaration but not the initialization.

JavaScript will not move variables that are declared and


initialized in a single line.

value of x will be undefined because var x = 1 is not


hoisted.
note :

That JavaScript compiler does not move function expression.


Window Object

The window object represents a window in browser.

An object of window is created automatically by the browser.

Window is the object of browser, it is not the object of javascript.

The javascript objects are string, array, date etc.


Unit II

DOM and DOM Events:


Document Object
The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object.

It is the root element that represents the html document.

The document object is a property of the window object.

It has properties and methods.

The document object is accessed with:

window.document or just document


What is the DOM?

It defines the logical structure of documents and the way a


document is accessed and manipulated.

The DOM is a W3C (World Wide Web Consortium) standard. The

DOM defines a standard for accessing documents.


update the content, structure, and style of a document.

DOM is a data representation of the objects in the HTML and XML


pages

DOM allows programmers access-adding, deleting ,and


manipulating-of all styles ,attributes ,and elements in a document.
Explain the DOM tree structure with a suitable
methods
DOM tree structure in detail along with suitable methods:

1. Document Node:
- The root node of the DOM tree, representing the entire HTML or XML
document.

- Accessible through the `document` object.

- Methods:
- `getElementById(id)`: Retrieves an element with the specified `id`
attribute.
- `getElementsByTagName(tagName)`: Retrieves a collection of
elements with the specified tag name.

`getElementsByClassName(className)`: Retrieves a collection of elements with the


specified class name.
- `querySelector(selector)`: Retrieves the first element that matches the specified CSS
selector. - `querySelectorAll(selector)`: Retrieves a collection of elements that match
the specified CSS selector.
2. Element Node:

- Represents an HTML or XML element, such as `<div>`, `<p>`, `<a>`,


etc.

- Methods:

- `getAttribute(name)`: Retrieves the value of the specified attribute.

- `setAttribute(name, value)`: Sets the value of the specified attribute.

- `appendChild(node)`: Appends a child node to the current element.

- `removeChild(node)`: Removes a child node from the current


element.

- `classList`: Provides methods to manipulate the classes of an element,


such as `add()`, `remove()`, `toggle()`, etc.

- `parentNode`: Retrieves the parent node of the current element.

- `childNodes`: Retrieves a collection of child nodes of the current


element.

3. Text Node: - Represents the text content within an element. - Accessible through the `nodeValue`
property of an element. - Methods: - `splitText(offset)`: Splits the text node into two separate text
nodes at the specified offset
4. Attribute Node:
- Represents an attribute of an HTML or XML element.
- Accessible through the `getAttribute(name)` and `setAttribute(name,
value)` methods of the element node.

5. Comment Node:
- Represents an HTML or XML comment within the document.
- Accessible through the `Node.COMMENT_NODE` property.

6. DocumentType Node: - Represents the document type declaration. - Accessible through


the `Node.DOCUMENT_TYPE_NODE` property. Certainly! Here are some additional details
on the DOM tree structure and methods:

8. Creating and Modifying Nodes: - The DOM provides methods for creating new nodes and
modifying existing nodes.

- Methods: - `createElement(tagName)`: Creates a new element node with the specified tag
name.
- `createTextNode(text)`: Creates a new text node with the specified text content. -
`createAttribute(name)`: Creates a new attribute node with the specified name. -
`appendChild(node)`: Appends a child node to the current node. - `removeChild(node)`:
Removes a child node from the current node. - `replaceChild(newNode, oldNode)`: Replaces
an existing child node with a new node.
9. Event Handling:
- The DOM allows you to attach event listeners to nodes to handle
various events.

- Methods:
- `addEventListener(event, callback)`: Attaches an event listener to
the
node.
- `removeEventListener(event, callback)`: Removes an event
listener
from the node
With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.
HTML DOM Document URL
The URL property returns the full URL of the document.
The activeElement property returns the HTML element
that have focus.
<!DOCTYPE html>
<html>
<body onclick="myFunction()">

<h1>The Document Object</h1>


<h2>The activeElement Property</h2>

<input type="text" value="An input field">


<button>CLICK HERE</button>

<p>Click anywhere in the document to display the active element:</p>

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

<script>
function myFunction() {
const element = document.activeElement.tagName;
document.getElementById("demo").innerHTML = element;
}
</script>

</body>
</html>
HTML DOM Document addEventListener()

The addEventListener() method attaches an event handler to a document.


<!DOCTYPE html>
<html>
<body>

<h1>The Document Object</h1>


<h2>The addEventListener() Method</h2>

<p>Click anywhere in the document to display "Hello World!".</p>

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

<script>
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World!";
});
</script>

</body>
</html>
HTML DOM Document documentElement

The documentElement property returns a document's element (as


an Element object).

For HTML documents the returned object is the <html>


element.
HTML DOM Document getElementById()
The getElementById() method returns an element with a specified
value.

The getElementById() method returns null if the element does not


exist.

The getElementById() method is one of the most common methods


in the HTML DOM.

It is used almost every time you want to read or edit an HTML


element.
Note

Any id should be unique, but:

If two or more elements with the same id exist, getElementById()


returns the first.
HTML DOM Document getElementsByName()
The getElementsByName() method returns a collection of elements
with a specified name.
HTML DOM Document getElementsByTagName()

The getElementsByTagName() method returns a collection of all


elements with a specified tag name.
getElementsByTagName("*") returns all elements in the
document.
HTML DOM Document write()
Document object method: querySelector() method
The Document method querySelector() returns the first Element
within the document that matches the specified selector, or group
of selectors. If no matches are found, null is returned.
Several elements which does not have id, then we cannot
access any element using

getElementById method
In order to access an element by class name we have another method

querySelector() method.

This method is present in document object.

This method returns web page elements by its class name, tag name.
Accessing and Modifying the DOM
Logical structure of the tree DOM :

We can add, modify and delete the elements.

Each element in a tree node

object
Element object
nodeType

The nodeType property returns the node type, as a number, of the


specified node.

If the node is an element node, the nodeType property will return 1.

If the node is an attribute node, the nodeType property will return 2.


getAttribute() method
hasAttribute() method
HTML DOM Element innerHTML

The innerHTML property sets or returns the HTML


content (inner HTML) of an element.
HTML DOM Element innerText

The innerText property sets or returns the text


content of an element.
To identify and access the DOM elements,
JavaScript uses three ways:

1. First, Accessing elements By ID

2. Second, Accessing elements By TagName

3. Third, Accessing elements By className


HTML DOM Document getElementsByClassName()
The getElementsByClassName() method returns a collection of
elements with a specified class name(s).
JavaScript Events

The change in the state of an object is known as an Event.

HTML DOM events allow JavaScript to register different event handlers on


elements in an HTML document.

When javascript code is included in HTML, javascript react


over these events and allow the execution.

This process of reacting over the events is called Event


Handling.

Thus, javascript handles the HTML events via Event


Handlers.
HTML or DOM events are widely used in JavaScript code.

JavaScript code is executed with HTML/DOM events.


EXPLAIN EvENT handlers

Certainly! Event handlers in HTML allow you to associate JavaScript code with
specific events that occur on HTML elements. They provide a way to respond to user
interactions or other events happening on the webpage. Event handlers can be
added directly as HTML attributes or attached dynamically using JavaScript. Here are
the key aspects of event handlers in HTML: 1. HTML Attribute Event Handlers: - Event
handlers can be added directly to HTML elements using attributes. - The attribute
name follows the format "on{event}", where {event} is the name of the event in
lowercase. - The attribute value contains JavaScript code that will be executed when
the event occurs.
2. JavaScript Event Handlers:
- Event handlers can also be attached dynamically using JavaScript.
- The `addEventListener()` method is used to bind an event handler to an
element.
- This method takes the event name and a callback function as
parameters.
- The callback function is executed when the specified event occurs on
the element.
3. Event Object:
- When an event occurs, an event object is created and passed as an
argument to the event handler function.
- The event object contains information about the event and provides
methods and properties to interact with it.
- It allows you to access event-specific details such as the target element,
event type, coordinates, and more.
What is Event propagation
The Event Propagation determines in which order
the elements receive the event.

An event travels or propagates through the DOM


tree, this is called Event propagation.

Propagation refers to how events travel through


the Document Object Model (DOM) tree.
There are two ways to handle this event propagation
order of HTML DOM

1.Event Bubbling

2.Event Capturing
Event Bubbling

Event bubbling is used where the event handlers are


invoked when one element is nested on to the other
element and are part of the same event.

This technique or method is known as Event Bubbling.


Is used where the event handlers are invoked
when one element is nested on to the other
element and are part of the same event
The button is a child of the span, which in turn is a child of
the div, and the div is a child of the body. The DOM tree
would look like this:
When you click the button, it is like you're also clicking the span (the blue background). This
is because the button is a child of the span.

It's also the same thing with the div and the body.
When you click the button, it's just like you're also clicking the span, div, and body because
they are the button's ancestors. This is the idea of event bubbling.
An event doesn't stop at the direct element that receives it.

The event bubbles up to its ancestors, until it gets to the root


element.

Also, if you click on the blue box (span), the button


doesn't receive the click event as it is not a parent or
ancestor or the span. But, the div, body, and HTML
would receive the event.
The addEventListener() method attaches an event handler to a document.
example,

You have assigned a onclick event handler on a hyperlink (i.e. <a> element) which is
nested inside a paragraph (i.e. <p> element).

Now if you click on that link, the handler will be executed.

They travel up and down through the DOM tree to reach their target. This is known as
event propagation
HTML DOM Document addEventListener()

The addEventListener() method attaches an event


handler to a document.
How to Stop Event Bubbling

Event Bubbling is a default behavior for events.

But in some cases, you might want to prevent this.

To prevent event bubbling, you use the stopPropagation


method of the event object.

stopPropagation and preventDefault are methods of the


event object for stopping default behaviors.
Stopping Bubbling

But a handler can also take decision to stop the bubbling when the
event has been processed completely.

In JavaScript, we use the event.stopPropagation () method.

• <body>
• <div id="p1">
• <button id="c1" onclick="event.stopPropagation()"> child</button>
• </div>
• <script>

when we click on the button, it will not work because event.stopPropagation ()


method is being invoked here due to which the parent function will not be
invoked.

event.stopImmediatePropagation () method.
It means when the user click on the
button, the click event flows in this order
from bottom to top.
Event Capturing
Event Capturing is opposite to event bubbling, where in event
capturing, an event moves from the outermost element to the
target.

addEventListener() has an optional third parameter - which takes


its argument as a Boolean - which controls the phase of the
propagation.

the addEventListener which accepts a Boolean value, passing


true will cause the listener to be on the capturing phase.

The default is false, which will apply it to the bubbling phase.


cookies in javascript
Web applications work on HTTP protocol which is a stateless protocol.

This means after the web server has processed the client request for a web page,
the web server will not remember anything about the client that made the
request.

The page does not remember the colour we selected earlier.

This is because web applications works on HTTP protocol which is a stateless


protocol.

Means after the web server has processed the initial client request ,it does not
remember anything about the settings the client made.
What are Cookies?
Cookies are small text files or a set of information(data) that is
stored on the user’s system or browser..

A cookies is basically a string of name-value pairs separated by semi-


colons.

Cookies let you store user information in web pages. You can store,

read, update, and delete data.


JavaScript Cookie is the best option to store data in the web pages
Cookies were invented to solve the problem of “how to remember information
about the user”.

A cookie can be used for authenticating, session tracking, remember specific


information about the user like his name, password, last visited date etc.

In javascript, we can create and retrieve cookie data with JavaScript's


document object's cookie property.

When any user visits any page of the website.

Cookies will remember their details by cookie.


How to create a Cookie in JavaScript?
In JavaScript, we can create, read, update and delete a
cookie by using

document.cookie property

During the browsing session, browser stores the cookies in memory, at the
time of quitting they goto the file called cookies.txt.

Different browser store cookies files in a different location in the disk


Cookie Attributes

There are six parts of a cookie : name, value, expires, path,


domain, and security.

The first two parts i.e. name and value are required and rest
parts are optional.
1. name and value

The first part of the cookie string must have the name and value.

The entire name/value must be a single string with no commas,


semicolons or whitespace characters.

Here is an example which stores the string "George" to a cookie


named “myName".

The JavaScript statement is :

document.cookie = "myName=George";
2.
Expires

The cookie has a very limited lifespan.

It will disappear when a user exits the browser.

To give more life to the cookies you must set an expiration date in the following
format.

DD-Mon-YY HH:MM:SS GMT

Here is an example where the cookie will live upto Mon, 12 Jun 2023:00:00:00
GMT

document.cookie = "VisiterName=John; expires=Mon, 12 Jun 2023:00:00:00


GMT; ";
you can use the Date object to get the current date, and then set a
cookie to expire six months or ten months.
3. Cookie path attribute

If a cookie is created for a webpage, by default, it is valid only


for the current directory and sub-directory.

JavaScript provides a path attribute to expand the scope of


cookie up to all the pages of a website.
www.w3resource.com/javascript/ sets a cookie then all the pages in that directory
(i.e. ../javascript) and its subdirectories will be able to read the cookie.

But a page in www.w3resource/php/ directory can not read the cookie.

Usually, the path is set to root level directory ( '/' ) , which means the cookie is
available for all the pages of your site.

If you want the cookie to be readable in a specific directory called php, add path=/php;.
Cookie domain attribute

A JavaScript domain attribute specifies the domain for


which the cookie is valid.

if we provide any domain name to the attribute


such like:

Here, the cookie is valid for the given domain and all its sub-domains.

domain=training.javatpoint.com

Here, the cookie is valid only for the given sub-domain. So, it's a better
approach to provide domain name instead of sub-domain.
Secure
The last part of the cookie string is the secure part which is a
Boolean value.

The default value is false.

If the cookie is marked secure (i.e. secure value is true) then the
cookie will be sent to web server and try to retrieve it using a
secure communication channel.

This is another way to securing our user information from


untrusted servers.
ReactJS
ReactJS

ReactJS is a efficient, and flexible JavaScript library for building reusable UI components.

It is an open-source, component-based front end library which is responsible only for


the view layer of the application.

ReactJS is an open-source javascript library designed by Facebook to create single page


web or mobile applications.

It encourages the creation of reusable UI components.

The main objective of ReactJS is to develop User Interfaces (UI) that improves the
speed of the apps.

React is used to build single-page applications.


It uses virtual DOM (JavaScript object), which improves the performance of the app.
It uses virtual DOM (JavaScript object), which improves the
performance of the app.

JavaScript virtual DOM is faster than the regular DOM.

We can use ReactJS on the client and server-side as well as with


other frameworks.

DOM is a part of the browser.


Manipulating original DOM is difficult and slow but Manipulating virtual DOM is very
fast.

So each time there is a change in the state of our application, virtual DOM gets updated
first instead of the real DOM.
Whenever there is any change in the state of the application UI,
DOM is updated and represents the change.
Every change for updating the application User Interface, which
affects the performance and slows it down.

using the 'getElementById()' or 'getElementByClass()' method to


modify the contents of DOM.

For example, the real and virtual DOM is represented as a tree structure.

React allows developer to create web apps which can change


data, without reloading the web page.

Every element in the tree is a node.

A node is added to the tree when a new item is added to the application UI.
Virtual Document Object Model(VDOM)

Reason why react works faster because it uses virtual DOM concept.

Concept is simple react creates a copy of current DOM structure in


a memory.

Every time any change happens within a DOM hierarchy it compares


current DOM with virtual DOM and finds the difference.

Finally, it updates only part of the DOM where these changes are
required.
The JavaScript virtual DOM is faster than the regular DOM.

We can use ReactJS on the client and server-side. React allow

us to create reusable UI components.

Single-Way data flow

In react application data flows in single direction from parent to


child components however event can flow from child to parent
components.
Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase
property naming convention instead of HTML attribute names.

For example, class becomes className in JSX, and tabindex becomes tabIndex
.

Handling events with React elements is very similar to handling events on DOM
elements. There are some syntax differences:

•React events are named using camelCase, rather than lowercase.


with plain HTML, to prevent the default form
behavior of submitting, you can write:

Another difference is that you cannot return false to prevent default behavior in React.
In react, we cannot return false to prevent the default behavior

You must call preventDefault() explicitly. For example, stopPropagation methods.


Synthetic Events
Different browsers may have different names for the events.

In React, synthetic events play a crucial role in handling DOM events


consistently across different browsers.

Reacts synthetic events ensure that event handling works


consistently across various browsers.

For one, with React, we have to name events using the camelCase
notation.

For example, in plain JavaScript, the click event is defined as onclick(),


while in React, we access the same event using onClick()
What Are Synthetic Events?

Synthetic events are cross-browser wrappers around the browser’s original events.

when a website is developed for multiple browsers, it is called a cross-browser website.

A cross-browser wrapper is a concept used in web development to ensure consistent behavior across
different web browsers.
cross-browser wrappers

This means the browsers may display the same Web page with slightly
different page and text formatting. Since not all browsers support the
same HTML tags

However, React SyntheticEvent registers an event’s name in different


browsers.

React SyntheticEvent provides, prevents browser inconsistencies,


and ensures that the event works across multiple platforms.
The React Events Syntax

To add events to react elements, we need two things:

An event listener
An event handler

Event Listener Attribute

To listen for events and detect them, we have to specify the event
listener attribute on the React/JSX element. The general form of this
attribute is:

Examples include onClick, onSubmit, onChange, etc.


Event handler

It’s a function/method that you, as a developer, pass as a


value to the event listener attribute.

It comes into action when the specified event on the


element occurs.
Unit III

Apache
Web pages
Are a collection of data, including images, text files, hyperlinks,
database files etc., all located on some computer (also known as
server space) on the Internet.

A web server is a software or programs or computer systems that


runs on the server-side.

When any user requests their web browser to run any web page, the
webserver places all the data materials together into an organized
web page and forwards them back to the web browser with the help
of the Internet. Therefore, we can conclude that: -

This intercommunication of a web server with a web browser is


done with the help of a protocol named HTTP (Hypertext Transfer
Protocol).
How web server works

HTTP PROTOCOL
Collection of web pages
Web Server

web sites
• Web server is a computer system that hosts
• Runs web server software Ex: Apache HTTP, Microsoft
• Connected to internet IIS

If the requested web page at the client side is not found,


then web server will sends the HTTP response:
.
Error 404 Not found.
Web Server

1. Shared hosts 2. Dedicated hosts


WEB SERVERS host web sites for multiple users.
Small or personal Web sites which will not have
any huge amount of traffic.

Some web servers host web sites for single user or


for the company.
Server types
1. Web server 2. application server 3. Database server
Application server
httpd Server
Why is Apache called HTTPd?
Apache HTTP Server, also known as httpd, is a web server.

When Apache is running under Unix, its process name is httpd , which is short for
"HTTP daemon/service".

That runs in the background as a process and processes all requests.

HTTPd waits for the incoming client requests and for each request it answers
by replying with requested information.
It listens to one or more TCP ports (usually port 80) for incoming requests
from browsers and serves the requested files accordingly.

this daemon runs as a standalone process which means it doesn’t depend on


any process to initiate.

It waits for requests from the web and forwards the request to the
appropriate processes.

When used like this it will create a pool of child processes or threads to handle
requests.

When this daemon used, it will create threads or a pool of child processes to
handle requests.

The Apache httpd is configured by placing the configuration file “httpd.conf” in


the respective directory, The default path of httpd.conf file is
etc/httpd/conf/httpd.conf
The Yellowdog Updater, Modified (YUM) is a
free and open-source command-line
package.
start Apache web server installation
yum install httpd

Start the Apache Server


service httpd start

Status of Apache service service


httpd status httpd is stopped

To restart the httpd daemon


service
service httpd restart

To Stop the httpd daemon service


service httpd stop
Request Response Formats Basics
Hyper Text Transfer Protocol communication allows two
types of messages to be transferred between the Client and
the server, HTTP Request and the HTTP Response.

The request is sent by the client/browser to the server and


the response is sent by the server to the browser.

Both the message have a common


format, they both contain a HTTP
Header and a HTTP Body.
Request Message: The request message is sent by the client that
consists of a request line, headers, and sometimes a body.
Format
:
HEAD: Retrieve Header
Information
▪ HEAD is identical to GET, except the server does not return
the content in the HTTP response.
▪ This will work much faster than using GET.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/'); exit;
?>
HTTP REQUEST STRUCTURE
REQUEST METHODS
There are three types of Request methods

▪ GET: Retrieve a Document

▪ POST: Send Data to the Server

▪ HEAD: Retrieve Header Information


GET: Retrieve a Document
▪ Used for retrieving html, images, JavaScript, CSS, etc.

▪ Example:
<form method="GET" action=“example.php">

First Name: <input type="text" name="first_name"/> <br />

Last Name: <input type="text" name="last_name"/> <br />

<input type="submit" name="action" value="Submit" />

</form>
▪ When that form is submitted, the HTTP request begins
like this:

▪ GET/example.php?first_name=John &last_name=Doe
&action=Submit HTTP/1.1
POST: Send Data to the Server
▪ POST requests are most commonly sent by web forms

▪ POST method requests can also be made via AJAX, applications, URL, etc.

Example:
<form method="POST" action=“example.php">

First Name: <input type="text" name="first_name"/> <br />

Last Name: <input type="text" name="last_name" /><br />

<input type="submit" name="action" value="Submit" />

</form>
 Submitting that form creates an HTTP request like this:

POST /example.php HTTP/1.1


Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5)
Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded Content-Length: 43

Output:
first_name=John &last_name=Doe &action=Submit
Response Message: The response message is sent by the server to the client that
consists of a status line, headers, and sometimes a body.

General Header

Request Header

Response Header

Entity Header
HTTP RESPONSE STRUCTURE
HTTP Status Codes
▪ 200's are used for successful requests.

▪ 300's are for redirections.

▪ 400's are used if there was a problem with the


Request.

▪ 500's are used if there was a problem with the server.

▪ 404 file not found


HTTP FUNCTIONS
▪ Header( ):Sends a raw HTTP header to a client.

▪ Headers list( ):Returns a list of response headers sent (or ready


to send).

▪ Headers sent( ):Checks if / where the HTTP headers have been


sent.

▪ Setcookie( ):Sends an HTTP cookie to a client.

▪ Setrawcookie( ):Sends an HTTP cookie without URL encoding


the cookie value.
2. Message Headers

The Message header provides information about the request and


response.

It also provides information about the object which is sent in the


message body.

Message Headers are of four types:

1. General Header:

General information about the communication such as the date and


time on which the request/response was generated.

This header is common to both Request and Response.

Example Date: Tue, 17 Nov 2020 16:39:15


2. Request Header :-

Contains information about the request such as the URL that you have
requested, the method(GET, POST, HEAD) ,the browser used to
generate the request and other info.

Ex: User-Agent:”Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0)

3. Response Header:

The server software that is used on the server machine to generate


the response.

Server: IIS
Most of the sites usually hide their server information.
4. Entity Header

This header contains information about the actual message or the


HTTP body that is being sent.

Information such as content


length(length of the
body), the language of the content,
encoding, expiration date .
Message Body

content/message body which is the actual data you want to


fetch.

The content can contain your HTML code or an image or your


CSS stylesheets, JavaScript files depending on the resource for
which you have made the request for.
FUNCTIONING GROUPS (REQUESTS)
 Requests
 http_get( )
 http_head( )
 http_post_data( )
 http_post_fields( )
 http_put_data( )
 http_put_file( )
 http_put_stream( )
 http_request_body_encode( )
 http_request_method_exists ( )
 http_request_method_name( )
 http_request_method_register( )
 http_request_method_unregister( )
 http_request( )
FUNCTIONING GROUPS (RESPONSES)
 Responses
 http_redirect( )
 http_send_content_disposition( )
 http_send_content_type( )
 http_send_data( )
 http_send_file( )
 http_send_last_modified( )
 http_send_status( )
 http_send_stream( )
 http_throttle( )
What is .htaccess File?
.htaccess (hypertext access) is a hidden file used to configure
additional features for websites hosted on Apache Web Server.

The .htaccess file is a website file that controls high-level


configuration of your websites.

On servers that run Apache (a web server software),

.htaccess file allows you to make changes to your website’s


configuration without having to edit server configuration files.

change domain names ( Redirect URLs)

you can rewrite URL, password-protect directories.


Common Uses of .htaccess File
Load custom error pages, like 404 pages

Force your site to use HTTPS(Hypertext Transfer


Protocol Secure) secure version of HTTP, instead
of HTTP

Password-protect certain directories on your server


Unit IV

AJAX
It is a group of inter-related technologies like JavaScript,
DOM, XML, HTML/XHTML, CSS,
XMLHttpRequest

AJAX allows you to send and receive data


asynchronously without reloading the web page. So it is
fast.
AJAX Technologies
HTML/XHTML and CSS
These technologies are used for displaying content and style. It is mainly
used for presentation.

DOM
•It is used for dynamic display and interaction with data. alter the
content and how it is displayed.

XML or JSON
which is used to transfer data between the server and Web browser (using XML) JSON (Javascript
Object Notation) is like XML but short and faster than XML.

XMLHttpRequest
It’s a object, For asynchronous communication between client and server.

JavaScript
It is used to bring above technologies together.

Independently, it is used mainly for client-side validation.


Clients request is
blocked

Brower's javascript
engine is blocked.
The original article that defined the term AJAX lists the following
technologies:
•XHTML and CSS, which defines what is being displayed and how it is
displayed.

•The Document Object Model, which allows us to programmatically alter the


content and how it is displayed.

•XML and XSLT, which is used to transfer data between the server and Web
browser (using XML), and to manipulate that data (using XSLT).

•XMLHttpRequest, which is the object used to communicate with the Web


server over HTTP. This object provides the asynchronous communication
abilities.

•JavaScript, which is the programming language implemented in most Web


browsers, and is used to bring together all the other technologies listed above.
Click

By JS

Thes server
processes
the request
All modern browsers (Chrome, Firefox, Edge , Safari, Opera
have a built-in XMLHttpRequest object.
output
It does not actually open the file or Web resource requested by the method.
Rather, it sets up a request for a file.
OUTPUT
AJAX - Server Response

The onreadystatechange Property

The readyState property holds the status of the


XMLHttpRequest.

The onreadystatechange property defines a function


to be executed when the readyState changes.

The status property and the statusText property


holds the status of the XMLHttpRequest object.
How AJAX works?

Server sends XML data or JSON data


to the XMLHttpRequest callback
function.
Server interacts
with the
database using
Data is retrieved
JSP, PHP,
Servlet, ASP.ne

XMLHttpRequest is a built-in browser object that allows to make HTTP requests in


JavaScript.
Using a Callback Function

1. A callback function is a function passed as a parameter


to another function.

2. If you have more than one AJAX task on your website,


you should create ONE standard function for
creating the XMLHttpRequest object, and call this for
each AJAX task.

3. The function call should contain the URL and what to


do on onreadystatechange (which is probably different
for each call):
XMLHttpRequest is a built-in browser object that allows to
make HTTP requests in JavaScript.
Advantages
• AJAX allows a Web page to only reload those portions which have
changed, rather than reloading the whole page.

This can substantially reduce the amount of bandwidth that the Web
application requires.

• Because AJAX allows for asynchronous communication, and for only


reloading a portion of a Web document, it allows the Web application
to be more frequently available to the user, since page reloads are
reduced, and the user can continue using the application while data is
being transmitted.
AJAX Database
AJAX can be used for interactive communication with a
database.

a function called "showCustomer()" is


executed. The function is triggered by the
"onchange" event:
AJAX XML Example
AJAX RSS Feeds

• Ajax (Asynchronous JavaScript And XML) and RSS (Really Simple Syndication)
or (Rich site summary) are two technologies.

• RSS Reader is used to read RSS Feeds.


• RSS Feeds are an easy way to stay up to date with your favorite
websites, such as blogs or online magazines, web series etc.
An Ajax RSS

An RSS feed is simply a link to an XML file .

For example, the title, author, and description tags are


required, and so all RSS XML files will have at least these three
tags.

using Ajax, we are passing over the work of processing the RSS
XML file to the web browser, thus reducing server load. Also,
because we are able to fetch the entire RSS XML file from the
server without having to refresh the page.

Lastly, Ajax is designed to handle XML files, so it's able to


parse RSS in a simple and elegant way.
1. The file name of the RSS feed is selected in an HTML form.

2. Once the user clicks Submit, the getRSS() function is called.

3. This function is responsible for fetching the specified RSS XML file
from the server.

4. Once it's fetched successfully, processRSS() converts the received XML


file into a JavaScript object.

5. Finally, showRSS(RSS) is called, which displays some of the information


contained in the RSS JavaScript object to us by updating the HTML page.

Selects file
fetches name of the
successful RSS feed
It contains a simple HTML form and a link to a
JavaScript:

The form works like this:

An event is triggered when the user selects an


option in the drop down box.

When the event is triggered, a function called


showRSS() is executed.

Below the form is a <div> called "rssOutput". This

is used as a placeholder for the return data of


the showRSS() function.
The showRSS() Function

Every time an option is selected in the input field this function executes the
following:

Defines the url (filename) to send to the server

Adds a parameter (q) to the url with the selected option from the drop down box

Adds a random number to prevent the server from using a cached file

Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells


the object to execute a function called stateChanged when a change is triggered.

Opens the XMLHTTP object with the given url.

Sends an HTTP request to the server


Unit V

AJAX Advanced
Cross-Origin Resource Sharing (CORS)
What is CORS?
There's a security policy that browsers follow.

It's called the Same-Origin Policy(SOP) which basically states only


resources from the same domain, host and port can interact with
each other.
For example,

example.com can retrieve data from its server at example.com because they share
the same domain.

Any of its subdomains would also be accessible (i.e. example.com/page1 or


example.com/page1/page2).

However, resources from domains like api.example.com or google.com would not


be accessible to example.com due to this security policy.

this policy is put in place for security purposes. Imagine if there's no


such restriction; a malicious site can simply GET any data from any
site resulting in cross-site request forgery(CSRF) attacks.
website is usually passed in the Access-Control-Allow-Origin
request header, which will tell the server that it is okay to send and share its
data to this website.

For example, if we set Access-Control-Allow-Origin to example.com, it means that


this website can now have access to api.example.com.
Security measures implemented by browsers
Popular web browsers like Chrome and Mozilla Firefox use this
security technique to determine which cross-site requests are
secure.

Modern browsers use the same-origin policy to limit access from


scripts to resources outside their domain for security concerns.
Resource will have certain policies to be shared with certain
domains.

For security reasons browsers restrict this CROSS ORIGINs HTTP


REQUEST, because the browser don’t know whether they should
trust the other Cross origin SERVER OR NOT.
Cross-Origin Resource Sharing (CORS)
Browser security feature that restricts cross origin HTTP requests

• Web technology mechanism

SERVER

Originating
How does CORS work?

CORS requests come in two types: simple requests and preflighted


requests

Simple requests:

A CORS request that doesn’t need to go through any preflight requests (initial
checks) is referred to as a simple request.
•AJAX request is started by a browser tab that is open to
https://www.mydomain.com. GET widgets at https://api.mydomain.com
•The browser automatically inserts the Origin Request Header along with headers
like Host for cross-origin requests
•The Origin request header is examined by the server. The Access-Control-Allow-
Origin is set to the value in the request header Origin if the Origin value is allowed.
•The Access-Control-Allow-Origin header is checked by the browser to verify if it
matches the origin of the tab when it receives the answer. If not, the reply is
suppressed.
Preflighted requests:
The other kind of CORS request is a preflighted request.

A preflighted request is a CORS request in which the browser must first make a
preflight request (also known as a preliminary ) to the server to determine
whether the original CORS request can be processed.

It is an additional HTTP request using the OPTIONS method.

The browser performs this for every unsafe request that is intended to alter data
— for example, POST, PUT, or DELETE requests.

We refer to the original CORS request as preflighted because it was preceded by a


preflight request.
Dynamic Script Loading

jQuery makes event handling, DOM manipulation, Ajax calls much easier
than JavaScript

AJAX is the art of exchanging data with a server, and updating parts of a web page
- without reloading the whole page.

jQuery provides several methods for AJAX functionality.

With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a
remote server using both HTTP Get and HTTP Post - And you can load the external
data directly into the selected HTML elements of your web page!
jQuery is a JavaScript Library. cross-platform

jQuery is a lightweight, "write less, do more", JavaScript library.

The main purpose of jQuery is to provide an easy way to use JavaScript on your website to make it
more interactive and attractive. It is also used to add animation.

It is cross-platform and supports different types of browsers.

Many of the biggest companies on the Web use jQuery, such as:

Google
Microsoft
IBM
Netflix
what is the need of jQuery or what difference it makes on bringing jQuery instead of AJAX/
JavaScript
jQuery - AJAX load() Method

returned into selected element without loading the whole page.


jQuery selectors allow you to select and manipulate HTML element(s).
The following example loads the content of the element with id="p1", inside
the file "demo_test.txt", into a specific <div> element:
The optional callback parameter specifies a callback function to run when
the load() method is completed.

The callback function can have different parameters: responseTxt -

contains the resulting content if the call succeeds


statusTxt - contains the status of the call
xhr - contains the XMLHttpRequest object
When the browser loads HTML and comes across a <script>...</script> tag, it
can’t continue building the DOM.

It must execute the script right now.

The same happens for external scripts <script src="..."></script>:

the browser must wait for the script to download, execute the downloaded
script, and only then can it process the rest of the page.

How to dynamically load a JS file in JavaScript


dynamically load a file called easy.js and append it to
the bottom of body element.
Image- Based AJAX
uploading a file with Ajax is very easy
Prototype Inheritance
OR

JavaScript Object Prototypes


properties
All JavaScript objects inherit prototype.
methods

In JavaScript, objects have a special hidden property


[[Prototype]]
Understanding how objects inherit properties in
JavaScript.
The prototype object

In JavaScript, objects have a special hidden property


[[Prototype]] , that is either null or references another
object. That object is called “a prototype”

In JavaScript, an object can inherit properties of another object.

The object from where the properties are inherited is named


prototype.

Example, you can make pet a prototype of cat which will


then inherit legs property. → HOW
JavaScript has only primitives types like null, undefined, and objects.

properties: key and value pairs.

For example, the following object cat contains 2 properties:

But how can I connect(objects) cat with pet? I can make pet a
prototype object for cat!
Following the example,

you can make pet a prototype of cat which will


then inherit legs property.

When creating an object using the object literal,

you can use the special property _ _proto _ _to


set the prototype of the created object.
Cat object inherits the property called legs from
prototype object pet.
Parrot

2
Parrot

Parrot 2

Parrot 2 2
Parrot
Parrot
Parrot
Parrot
A Regular expression is a string that describes a pattern
e.g., email addresses and phone numbers.

A regular expression is a sequence of characters that


forms a search pattern.

In JavaScript, regular expressions are objects.

JavaScript provides the built-in RegExp type that allows


you to work with regular expressions effectively.
Regular expressions can be used to perform all types of text search and text replace
operations.

Regular expressions are useful for searching and replacing strings that match a pattern.
Self-describing data is the data that describes both its content and
structure.
HI
The root element in the example is <bookstore>. All elements in the
document are contained within <bookstore>.

The <book> element has 4 children: <title>,< author>, <year> and <price>.
XML parsers are also known as XML Processor .

For reading the content and write the contents into the XML file W3C organization
have provided some programs. Those programs are called as parsers.

XML parser validates the document and check that the document is well
formatted.

Parsers are the programs which are meant for manipulating the data on the
XML file.
The goal of a parser is to transform XML into a readable code. transforming
it into a readable format for applications and systems to use
Two different parsers :
SAX (Simple API for XML)

1. Simple API for XML(Read only parser which is used for reading the content
from an XML file. This API is an event based API

It does not create any internal structure

It is very fast and works for huge documents.

It is preferred for larger documents. (because it will not occupy much memory)

2. DOM parser used for performing all kinds of manipulations on XML files.

Reading the content, updating, writing, deleting, replacing


Consumes more time

Reads entire document The SAX parser is less time consuming.

Reads node by node


JSON is a plain text written in JSON.

JSON supports arrays, objects , strings, numbers and values.

JSON is used to send data between computer.

Both JSON and XML can be used to receive data from a web server

A JavaScript program can easily convert JSON data into JS objects.

Java Script has a built in function for converting JSON strings into
Java Script objects.

JSON.parse()
JSON and XML examples both define an employees object, with
an array of 3 employees:
XML has to be parsed with an XML parser. JSON can be parsed by a
standard JavaScript function.
Both JSON and XML can be fetched with an XMLHttpRequest
AJAX RSS Feeds

• Ajax (Asynchronous JavaScript And XML) and RSS (Really Simple


Syndication) or (Rich site summary) are two technologies.

• RSS Reader is used to read RSS Feeds.


• RSS Feeds are an easy way to stay up to date with your
favorite websites, such as blogs or online magazines, web
series etc.
XSLT is used to transform XML documents
into XHTML documents, or into other
XML documents
Personal digital assistant
<channel> element. This element is used
to describe the RSS feed.
1. Explain in detail about MIME. (6 marks)

2. What is JavaScript? Explain the role of arrays, functions with suitable


examples. (10 marks)

3. Differentiate between HTML,HTML5 elements and its attributes (6


marks)

4. Define local storage, session storage with suitable examples. (6 marks)

5. Define Document Object Model(DOM) and list out various events


present in it.(6 marks)
1. List out various key and form related events in Document Object
Model(DOM). (6 marks)

2. Explain in detail about Document Object Model(DOM) event


propagation. (10 marks)

3. What are Web workers in HTML? How to create a web workers in


HTML? (10 marks)

4. What are Cookies? Explain its attributes. (10 marks)


1. AJAX RSS Feeds : What is RSS, why use RSS, who should use
RSS → Adarsha J K

2. JS Regular Expressions and examples → Aishwarya M

3. JS Regular Expression Modifiers, examples → Bindu G

4. Regular Expression patterns, examples→ Darshan Kumar

5. Introduction to XML → Deepika , Madhu , Chandan


Introduction to XML : Deepika , Madhu , Chandan
1. What is AJAX? Explain the structure of Request- Response mechanism in AJAX?

2. Explain Event Propagation and ways of event propagation.

3. Difference between GET and POST in HTTP methods.

4. Explain Array as object in JS and illustrate any four array methods.

5. What is event handler? Explain AddEventListener() to register event handlers.

6. What is XMLHttpRequest? What are the properties of XMLHttpRequest?

7. Define Apache web server. Write features of Apache web server.

8. Explain http configuration files use in web server.

9. Explain database access mechanism in AJAX with suitable example.

You might also like