Internet Programming-1
Internet Programming-1
Module-wise PYQs
Presentation Tier
The presentation tier is the user interface and communication layer of the application, where the end
user interacts with the application. Its main purpose is to display information to and collect
information from the user. This top-level tier can run on a web browser, as a desktop application, or a
graphical user interface (GUI), for example. Web presentation tiers are usually developed using HTML,
CSS and JavaScript. Desktop applications can be written in a variety of languages depending on the
platform.
Database Tier
The application tier, also known as the logic tier or middle tier, is the heart of the application. In this
tier, information collected in the presentation tier is processed - sometimes against other information
in the data tier - using business logic, a specific set of business rules. The application tier can also add,
delete or modify data in the data tier.
Advantages:
● Improved Data Integrity
● High Degree of Flexibility in deployment platform and configurations
● Improved security
● High Performance and persistent objects
● Architecture is scalable, adding users and resources in future would be easy
● Maintenance and modifications can be done effectively
● Code and data reusability can be achieved
Disadvantages:
● 3 tier architecture is complex compared to 1 tier and 2 tier
● Cost of network maintenance and deployment is greater than 1 tier and 2 tier
Write HTML5 code for embedding the audio and video elements in the
web page.(2019, 2018)
The <video> element
The <video> element allows you to embed a video very easily. A really simple example looks
like this:
<video src="rabbit320.webm" controls>
</video>
● The <audio> element doesn't support the width/height attributes — again, there is no
visual component, so there is nothing to assign a width or height to.
● It also doesn't support the poster attribute — again, no visual component.
The <canvas> element is only a container for graphics. You must use JavaScript to
actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding
images. A canvas is a rectangular area on an HTML page. By default, a canvas has
no border and no content. The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
The <canvas> is initially blank, and to display something, a script first needs to
access the rendering context and draw on it.
The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter,
the type of context2d.
Following is the code to get required context along with a check if your browser
supports <canvas> element −
var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// drawing code here
} else {
CSS Transitions
CSS transitions provide a way to control animation speed when changing CSS properties.
Instead of having property changes take effect immediately, you can cause the changes in a
property to take place over a period of time. For example, if you change the color of an element
from white to black, usually the change is instantaneous. With CSS transitions enabled,
changes occur at time intervals that follow an acceleration curve, all of which can be
customized.
CSS Transitions are controlled using the shorthand transition property. This is the
best way to configure transitions, as it makes it easier to avoid out of sync
parameters, which can be very frustrating to have to spend lots of time debugging
in CSS. You can control the individual components of the transition with the
following sub-properties:
transition-property
Specifies the name or names of the CSS properties to which transitions should be
applied. Only properties listed here are animated during transitions; changes to all
other properties occur instantaneously as usual.
transition-duration
Specifies the duration over which transitions should occur. You can specify a single
duration that applies to all properties during the transition, or multiple values to
allow each property to transition over a different period of time.
transition-timing-function
Specifies a function to define how intermediate values for properties are
computed. Timing functions determine how intermediate values of the transition
are calculated. Most timing functions can be specified by providing the graph of
the corresponding function, as defined by four points defining a cubic bezier.
transition-delay
Defines how long to wait between the time a property is changed and the
transition actually begins.
Transition shorthand CSS syntax
div {
transition: <property> <duration> <timing-function> <delay>;
}
This simple example performs a four-second font size transition with a two-second
delay between the time the user mouses over the element and the beginning of the
animation effect:
#delay {
font-size: 14px;
transition-property: font-size;
transition-duration: 4s;
transition-delay: 2s;
}
#delay:hover {
font-size: 36px;
}
Basics of Bootstrap
Bootstrap is a free and open-source tool collection for creating responsive websites
and web applications. It is the most popular HTML, CSS, and JavaScript
framework for developing responsive, mobile-first websites. Nowadays, the
websites are perfect for all browsers (IE, Firefox, and Chrome) and for all sizes of
screens (Desktop, Tablets, Phablets, and Phones).
Why use Bootstrap ?
By using this framework we can easily manipulate the styling of any web page, like
font style, text color, background color, flex, grid system, etc. Bootstrap V4 & V5
are the most popular versions. There are lots of other CSS frameworks like
Tailwind CSS, Bulma, and Foundation but among them, this framework is the
most popular because:
● It is Faster and Easier way for Web-Development.
● It creates Platform-independent web-pages.
● It creates Responsive Web-pages.
● It designs responsive web pages for mobile devices too.
● It is a free and open-source framework available on www.getbootstrap.com
For example, if the user clicks a button on a webpage, you might want to react to
that action by displaying an information box. In this article, we discuss some
important concepts surrounding events, and look at how they work in browsers.
This won't be an exhaustive study; just what you need to know at this stage.
Events are fired inside the browser window, and tend to be attached to a specific
item that resides in it. This might be a single element, a set of elements, the HTML
document loaded in the current tab, or the entire browser window. There are many
different types of events that can occur.
For example:
● The user selects, clicks, or hovers the cursor over a certain element.
● The user chooses a key on the keyboard.
● The user resizes or closes the browser window.
● A web page finishes loading.
● A form is submitted.
● A video is played, paused, or ends.
● An error occurs.
To react to an event, you attach an event handler to it. This is a block of code
(usually a JavaScript function that you as a programmer create) that runs when
the event fires. When such a block of code is defined to run in response to an
event, we say we are registering an event handler.
JS
const btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random() * (number+1));
}
btn.addEventListener('click', () => {
const rndCol = `rgb(${random(255)}, ${random(255)},
${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
Event Description
Explain Geo Location and media query with an example in HTML5 and
CSS3.
Geo-location in HTML5 is used to share the location with some websites and
be aware of the exact location. It is mainly used for local businesses, restaurants,
or showing locations on the map. It uses JavaScript to give latitude and longitude
to the backend server. Most of the browsers support Geolocation API. Geo-location
API uses a global navigator object which can be created as follows:
var loc = navigator.geolocation;
function getLoc() {
loc.getCurrentPosition(showLoc, errHand);
}
or
function getlocation(){
navigator.geolocation.getCurrentPosition(showLoc, errHand);
}
Output
Media queries allow you to apply CSS styles depending on a device's general
type (such as print vs. screen) or other characteristics such as screen resolution or
browser viewport width. Media queries are used for the following:
1. To conditionally apply styles with the CSS @media and @import at-rules.
2. To target specific media for the <style>, <link>, <source>, and other HTML
elements with the media= attribute.
3. To test and monitor media states using the Window.matchMedia() and
MediaQueryList.addListener() JavaScript methods.
SYNTAX
A media query is composed of an optional media type and any number of media
feature expressions, which may optionally be combined in various ways using
logical operators. Media queries are case-insensitive.
Following @media rule uses two media queries to target both screen and print
devices:
@media screen, print {
/* ... */
}
Say if we want to make a website responsive for widescreens or mobile phone
screens, then we will add media query which automatically change size of elements
on the page to look as intended.
To limit the styles to devices with a screen, you can chain the media features to the
screen media type:
@media screen and (min-width: 30em) and (orientation:
landscape) {
/* ... */
}
Following rule will apply its styles if the user's device has either a minimum height
of 680px or is a screen device in portrait mode:
@media (min-height: 680px), screen and (orientation: portrait)
{
/* ... */
}
A global variable, window, representing the window in which the script is running,
is exposed to JavaScript code.
We can associate methods with the window object to perform certain actions,
some are given as follows
Method Description
prompt() Displays a dialog box that prompts the visitor for input
Earlier days XML used to be the only option available for data exchange. Various
developments in the field of data processing and interchanging have made JSON as
an emergent alternative to XML due to number of reasons, such as
2. JSON parses data faster than XML by using standard JavaScript functions.
JSON is parsed into a ready-to-use JavaScript object.
3. XML is much more difficult to parse than JSON by using an XML parser.
5. Since the JSON format is text only, it can easily be sent to and from a server,
and used as a data format by any programming language.
8. JSON requires less tags than XML – XML items must be wrapped in open
and close tags whereas in JSON just name the tag once.
10. Data in XML is arranged in a tree format, which is not always the same
structure as the original data. JSON scores over XML with its map data
structure that matches with the actual data which makes the interpretation
easy and data arrangement more predictable.
11.JSON data structure helps in building RESTful APIs providing simpler data
exchange methods.
12. JSON applies the same data representation method as done in the code.
Hence, many languages can just slurp in JSON to find their own domain
object with ease. JSON allows easy transition of its objects from JSON object
to the objects in code. In XML, this transition is difficult because there is no
alignment between the objects in XML and those in the code.
13. JSON has a limited set of objects that can be modeled. So, in JSON
developers can create simple, more predictive and easy-to-read code.
Whereas in XML, we have more objects that can be modeled and developers
are unrestricted in using any of the user-defined objects. This makes XML
more complex and difficult to read.
Explain with proper syntax and examples how to use different types of
CSS Selectors.
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other
terms that tell the browser which HTML elements should be selected to have the
CSS property values inside the rule applied to them. The element or elements
which are selected by the selector are referred to as the subject of the selector. CSS
selectors define the pattern to select elements to which a set of CSS rules are then
applied. CSS selectors can be grouped into the following categories based on the
type of elements they can select.
Basic selectors
Universal selector
Selects all elements. Optionally, it may be restricted to a specific namespace or to
all namespaces.
Syntax: elementname
Class selector
Selects all elements that have the given class attribute.
Syntax: .classname
ID selector
Selects an element based on the value of its id attribute. There should be only one
element with a given ID in a document.
Syntax: #idname
Attribute selector
Selects all elements that have the given attribute.
Example: [autoplay] will match all elements that have the autoplay attribute set
(to any value).
Grouping selectors
Selector list
The , selector is a grouping method that selects all the matching nodes.
Example: div, span will match both <span> and <div> elements.
Combinators
Descendant combinator
The " " (space) combinator selects nodes that are descendants of the first element.
Syntax: A B
Example: div span will match all <span> elements that are inside a <div>
element.
Child combinator
The > combinator selects nodes that are direct children of the first element.
Syntax: A > B
Example: ul > li will match all <li> elements that are nested directly inside a
<ul> element.
Example: p ~ span will match all <span> elements that follow a <p>,
immediately or not.
Syntax: A + B
Example: h2 + p will match the first <p> element that immediately follows an
<h2> element.
Example: a:visited will match all <a> elements that have been visited by the
user.
Pseudo elements
The :: pseudo represents entities that are not included in HTML.
Example: p::first-line will match the first line of all <p> elements.
Explain JSON mashups in detail with a neat diagram.
A Mashup (also known as web application hybrid), is a technique that websites use
to provide resources, functionalities, and services from multiple sources. To put it
in layman’s terms, a mashup works as an aggregator of different services. They
mostly use public APIs that are generally free to use and thus, create a new service
from existing ones.
The readability and simplicity features of JSON have made it one of the most
popular notations in the mashup community. JSON, being a notation, provides a
way in which objects are written so that human beings can read it easily. It has a
built-in JavaScript feature that makes JSON a viable mashup technology. The
architecture of mashups in JSON implementation is shown in the above figure.
The flow of JSON mashups that use dynamic Script method goes in the following
steps:
1. The flow of the process starts with the browser sending request to the server
by using HTTP GET.
2. The Web Server responds with a page that includes the following couple of
important JavaScript functions:
a. A parsing function that expects JavaScript objects to be parameters.
b. The Dynamic Script method is the core of the initiation script through
which a new script tag is added to the page, specifying the source for
that script tag to be the Uniform Resource Locator (URL) at some
partner site.
3. The source code for the new script tag gets loaded by the browser.
4. Amazon receives an HTTP Get request sent from the browser using the
loaded script.
5. A JavaScript object, after being serialized into a JSON Object, is served by the
partner site.
6. A function call to the render function wraps the JSON script, and the
JavaScript entirely becomes the content for the script tag.
7. The new piece of JavaScript is tried for execution by the browser, which calls
the render method from step 2(a).
8. The server invokes the render method and evaluates the JSON script, which is
converted into a JavaScript object. The data contained in the render method
is pushed into the page after the render method, which uses the new
JavaScript object in its execution
DHTML with JS
DHTML stands for Dynamic HTML. Dynamic means that the content of the web
page can be customized or changed according to user inputs i.e. a page that is
interactive with the user. In earlier times, HTML was used to create a static page.
It only defined the structure of the content that was displayed on the page. With
the help of CSS, we can beautify the HTML page by changing various properties
like text size, background color etc. The HTML and CSS could manage to navigate
between static pages but couldn’t do anything else. If 1000 users view a page that
had their information for example Admit card, then there was a problem because
1000 static pages for this application have to be built to work. As the number of
users increases, the problem also increases and at some point it becomes
impossible to handle this problem.
● It is used for designing the animated and interactive web pages that are
developed in real-time.
● DHTML helps users by animating the text and images in their documents.
● It allows the authors for adding the effects on their pages.
● It also allows the page authors for including the drop-down menus or rollover
buttons.
● This term is also used to create various browser-based action games.
● It is also used to add the ticker on various websites, which needs to refresh
their content automatically.
Features of DHTML
● Its simplest and main feature is that we can create the web page dynamically.
● Dynamic Style is a feature, that allows the users to alter the font, size, color,
and content of a web page.
● It provides the facility for using the events, methods, and properties. And,
also provides the feature of code reusability.
● It also provides the feature in browsers for data binding.
● Using DHTML, users can easily create dynamic fonts for their web sites or
web pages.
● With the help of DHTML, users can easily change the tags and their
properties.
● The web page functionality is enhanced because the DHTML uses a
low-bandwidth effect.
It is used for developing and creating web pages. It is used for creating and designing
This markup language creates static web pages. This concept creates dynamic web pages.
It does not contain any server-side scripting code It may contain the code of server-side scripting.
The files of HTML are stored with the .html or The files of DHTML are stored with the
A simple page which is created by a user A page which is created by a user using the
without using the scripts or styles called as HTML, CSS, DOM, and JavaScript
This markup language does not need This concept needs database
Exception Handling in JS
An exception signifies the presence of an abnormal condition which requires special operable
techniques. In programming terms, an exception is the anomalous code that breaks the normal
flow of the code. Such exceptions require specialized programming constructs for its execution.
Exception handling is a process or method used for handling the abnormal statements in the
code and executing them. It is used to keep the flow control of the code/program intact. For
handling the code, various handlers are used that process the exception and execute the code.
For example, the Division of a non-zero value with zero will always result infinity, and it is an
exception. Thus, with the help of exception handling, it can be executed and handled.
Types of Errors
1. Syntax Error: When a user makes a mistake in the predefined syntax of a programming
language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program, such an error is
known as Runtime error. The codes which create runtime errors are known as Exceptions. Thus,
exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program that may
not produce the desired output, and may terminate abnormally. Such an error is known as
Logical error.
catch ( exception e )
{
// The code will run when there is an exception
[break;]
}
//-->
</script>
<html>
<head>
<title>Error and Exception handling</title>
<script type="text/javascript">
function First() {
var a = 123;
var b = 145;
var c = a + b;
try {
alert("Value of a: " + a );
alert("Value of b: " + b );
alert("Sum of a and b: " + c);
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
</script>
</head>
<body>
<p>Click the GfG button to see the result:</p>
<form>
<input type="button" value="Click GfG" onclick="First();" />
</form>
</body>
</html>
Module 3: Back End Development
What are servlets? Demonstrate servlet architecture and explain its working principle.
Servlet is one of the server-side programming language which runs on Java enabled server. It is used to
develop web based applications. As it is built on Java platform, servlet is fully compatible with Java
classes and interfaces. Let’s see what are servlets, Java servlets architecture and advantages of servlets
in detail.
Advantages Of Servlets :
1. As servlets support all protocols like FTP, SMTP, HTTP etc. they can be used to develop any kind
of web applications like E-commerce, Content management systems, chat based or file based web
applications etc.
2. As servlets are fully compatible with Java, you can make use of a wide range of available Java
APIs inside the servlets.
3. As they run on Java enabled servers, You need not to worry about garbage collection and memory
leaks. JVM handles them for you.
4. Since servlets are written in Java, they are portable and platform independent. You can run them
on any operating system and on any web servers available today.
5. Servlets inherit security features from JVM and web servers.
6. As servlets are written in Java, you can extend them according to your requirements.
7. As servlets are compiled into bytecodes, they are faster than any other server-side scripting
languages.
Disadvantages
01. Designing a servlet can be pretty laborious.
02.Exceptions need to be handled while designing a servlet since they are not thread-safe.
03.Developers may need additional skills to program a servlet.
JSP Lifecycle
A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet
life cycle with an additional step which is required to compile a JSP into servlet.
1. init()
The init() is the germinating stage of any Java Servlet. When a URL specific to a particular
servlet is triggered, the init() method is invoked. Another scenario when the init() method gets
invoked is when the servers are fired up. With every server starting up, the corresponding
servlets also get started, and so does the init() method. One important specialty of the init()
method is the init() method only gets invoked once in the entire life cycle of the Servlet, and
the init() method will not respond to any of the user's commands.The init() method Syntax:
2. service()
The service() method is the heart of the life cycle of a Java Servlet. Right after the Servlet's
initialization, it encounters the service requests from the client end. The client may request
various services like:
● GET
● PUT
● UPDATE
● DELETE
The service() method takes responsibility to check the type of request received from the client
and respond accordingly by generating a new thread or a set of threads per the requirement and
implementing the operation through the following methods.
● doGet() for GET
● doPut() for PUT
● doUpdate() for UPDATE
● doDelete() for DELETE
3. destroy()
Like the init() method, the destroy() method is also called only once in the Java Servlet's entire
life cycle.When the destroy() method is called, the Servlet performs the cleanup activities like,
● Halting the current or background threads
● Making a recovery list of any related data like cookies to Disk.
After that, the Servlet is badged, ready for the Garbage collector to have it cleared.
The destroy() method Syntax:
public void destroy() {
//destroy() method finalizing
}
HTTP is stateless, which means each request is considered as the new request. It is shown in the figure
given below:
1. Cookies: A cookie is a small piece of information that is persisted between the multiple client
requests. A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number. By default, each request is
considered as a new request. In cookies technique, we add cookies with response from the
servlet. So the cookie is stored in the cache of the browser. After that if a request is sent by the
user, a cookie is added with the request by default. Thus, we recognize the user as the old user.
JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent
connectivity between the Java programming language and a wide range of databases. The JDBC library
includes APIs for each of the tasks mentioned below that are commonly associated with database
usage.
● Making a connection to a database.
● Creating SQL or MySQL statements.
● Executing SQL or MySQL queries in the database.
● Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables, such
as −
● Java Applications
● Java Applets
● Java Servlets
● Java ServerPages (JSPs)
● Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take advantage
of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −
● JDBC API − This provides the application-to-JDBC Manager connection.
● JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity
to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases. Following is the architectural diagram, which shows the location of
the driver manager with respect to the JDBC drivers and
the Java application −
The JDBC API provides the following interfaces and classes − JDBC Architecture
● DriverManager − This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
connection.
● Driver − This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.
● Connection − This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with the database is through
connection objects only.
● Statement − You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored procedures.
● ResultSet − These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
● SQLException − This class handles any errors that occur in a database application.
The form is very simple which contains three fields: first name, last name, and email. In addition, It
contains the submit button which users can submit when he/she finish entering the data. In the form
tag, you can see it uses the post method to post the form data to the server. We need to create a JSP file
that is responsible for getting and processing the form’s data. The following is the handleUserInfo.jsp
form:
<html>
<head>
<title>JSP Form Demo</title>
</head>
<body>
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
%>
<p>Hi <%=firstName%> <%=lastName%>!,
your submitted email is <%=email%>.</p>
</body>
</html>
Characteristics of RIA
● Performance - RIAs can often perform better than traditional applications on the basis of the
characteristics of network and applications, performance of server also improved by offloading
possible processing work to the client system and also perceived performance in terms of UI
responsiveness and smoother visual transitions and animations are key aspects of any RIA.
● Offline use - When connectivity is unavailable, it might still be possible to use an RIA. An RIA
platform let the user work with the application without connecting to the Internet and
synchronizing it automatically when the user goes live.
● Consistency of look and feel - With RIA tools, the user interface and experience with
different browsers, devices and operating systems can be more carefully controlled and made
consistent.
● Security - RIAs should be as secure as any other web application, and the framework should be
well equipped to enforce limitations appropriately when the user lacks the required privileges,
especially when running within a constrained environment such as a sandbox.
● Rapid Development - An RIA Framework should facilitate rapid development of a rich user
experience through its easy-to-use interfaces in ways that help developers.
● Direct Interaction - An RIA can use a wider range of controls that allow greater efficiency and
enhance the user experience. In RIAs, for example, users can interact directly with page elements
through editing or drag-and-drop tools. They can also do things like pan across a map or other
image.
● Better Feedback - Because of their ability to change parts of pages without reloading, RIAs can
provide the user with fast and accurate feedback, real-time confirmation of actions and choices,
and informative and detailed error messages.
● A browser built-in XMLHttpRequest object (to request data from a web server)
● JavaScript and HTML DOM (to display or use the data)
AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally
common to transport data as plain text or JSON text. 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.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser without reloading the page.
Advantages of AJAX
1. Reduce server traffic and increase speed
2. Enable asynchronous calls: Ajax benefits web developers in how its framework can be used
for lazy loading. Those who don’t know what Lazy Loading is are an optimization technique that’s
widely used for online content. In essence, Ajax allows its users to make asynchronous calls to the
web server without reloading the whole web page. As a web visitor, you don’t have to wait for the
entire page to load entirely in order to access the entire page content. The concept of lazy loading
assists in loading only the required section and delays the remaining, until it is needed by users.
Thus, Ajax Lazy Loading not only improves a web page load it also has a positive impact on user
experience and conversion rates.
3. XMLHttpRequest is a request type widely used for sending a request to Ajax pages. You can
also call it with a different name: Asynchronous HTTP request.
4. Reduce bandwidth usage
5. Form Validation In contrast to traditional form submission, where client-side validations
occur after submission, the AJAX method enables precise and immediate form validation. AJAX
provides speed, which is also one of its significant benefits.
Disadvantages of AJAX
● Open-source. View source is allowed, and anyone can view the code source written for Ajax,
which makes it less secure compared to other technologies
● Search Engines cannot index Ajax pages can not be indexed by Google as well as other search
engines
● The usage of Ajax can cause difficulties for your web pages to debug as well as make them prone
to possible security issues in the future
● Most importantly, Ajax has a considerable dependency on JavaScript, so only browsers that
support Javascripts or XMLHttpRequest can use pages with Ajax techniques
● Users will find it challenging to bookmark a specific state of the application due to the dynamic
web page.
● From the users’ perspective, when you click the back button on the browser, you may not return
to the previous state of the page but the entire page. This happens because the pages with
successive Ajax requests are unable to register with the browser’s history
Draw the diagram for AJAX Web application model and Tradition Web Application
model and compare them.
● Most user actions in the interface trigger an HTTP request back to a web server. The server does
some processing, retrieving data, crunching numbers, talking to various legacy systems and then
returns an HTML page to the client.
● It’s a model adapted from the Web’s original use as a hypertext medium, but as fans of The
Elements of User Experience know, what makes the Web good for hypertext doesn’t necessarily
make it good for software applications.
● This approach doesn't make for a great user experience. While the server is doing its thing, the
user waits. And at every step in a task, the user waits some more.
● Obviously, if we were designing the Web from scratch for applications, we wouldn’t make users
wait around. Once an interface is loaded, why should the user interaction come to a halt every
time the application needs something from the server? In fact, why should the user see the
application go to the server at all?
Ajax Working
● An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by
introducing an intermediary Ajax engine between the user and the server. It seems like adding a
layer to the application would make it less responsive, but the opposite is true.
● Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine written
in JavaScript and usually tucked away in a hidden frame.
● This engine is responsible for both rendering the interface the user sees and communicating with
the server on the user’s behalf.
● The Ajax engine allows the user’s interaction with the application to happen asynchronously —
independent of communication with the server. So the user is never staring at a blank browser
window and an hourglass icon, waiting around for the server to do something.
HTML is used to display data and focuses on XML is a software and hardware
markup languages.
programming language.
HTML has its own predefined tags. You can define tags according to your need.
In HTML, it is not necessary to use a closing tag. XML makes it mandatory to use a closing tag.
HTML is static because it is used to display data. XML is dynamic because it is used to
transport data.
employee.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.javatpoint.com"
xmlns="http://www.javatpoint.com"
elementFormDefault="qualified">
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Employee.xml
<?xml version="1.0"?>
<employee
xmlns="http://www.javatpoint.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="./employee.xsd">
<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>[email protected]</email>
</employee>
Function strlen() - To count the number of characters in a string strlen() function is used.
<?php
$str = "Ques10";
echo "The length of string is:".strlen($str);
?>
// Displays: The length of string is:6
Function str_replace() - Replaces some characters in a string. str_replace() is case-sensitive, but we can
also use its case-insensitive sibling str_ireplace() to avoid case-sensitiveness.
<?php
$oldstr = "The cat was black";
$newstr = str_replace("black", "white", $oldstr);
echo $newstr;
?>
// Displays: The cat was white
Functions strtoupper() & strtolower() - Converts a string into uppercase and lowercase respectively.
<?php
$str1 = "Example of uppercase Function.";
$str2 = "Example of LOWERCASE Function.";
$case1 = strtoupper($str1);
$case2 = strtolower($str2);
echo $case1;
echo "<br>";
echo $case2;
?>
/* Displays: EXAMPLE OF UPPERCASE FUNCTION.
example of lowercase function.*/
Function ucwords() - This function capitalized the first letter of each word.
<?php
$str = "example of PHP string function.";
$cased = ucwords($str);
echo $cased;
?>
// Displays: Example Of PHP String Function.
Function str_repeat() - It is used to repeat same string for a specific number of times.
<?php
$str = “Ques10 ”
Echo “The Repeated string is:”.str_repeat($str , 4);
?>
// Displays: The Repeated string is: Ques10 Ques10 Ques10 Ques10
● A cookie is a small text file that is stored on the user's computer. The maximum file size of a
cookie is 4KB. It is also known as an HTTP cookie, web cookie, or internet Cookie. Whenever a
user visits a website for the first time, the site sends packets of data in the form of a cookie to
the user's computer.
● The cookies help the websites to keep track of the user's browsing history or cart information
when they visit their sites.
● It stores only the "String" data type.
● The information stored within cookies is not secure because this information is stored in
text-format on the client-side, which can be read by anyone.
● We can enable or disable the cookies as per the requirement.
● The cookies generated by a user are only be shown to them, and no other user can see those
cookies.
● Cookies are created and shared between the server and browser with the help of an HTTP
header.
● The path where the cookies are saved is decided by the browser, as Internet explorer usually
stored them in Temporal Internet File Folder.
● When we visit YouTube channel and search for some songs, next time whenever we visit
YouTube, cookies read our browsing history and shows similar songs or last played songs.
Session Cookies
A session stores the variables and their Cookies are stored on the
values within a file in a temporary user's computer as a text file.
directory on the server.
The session ends when the user logout Cookies end on the lifetime set by
from the application or closes his the user.
web browser.
It can store an unlimited amount of data. It can store only limited data.
In PHP, to set a session data, the In PHP, to get the data from cookies,
$_SESSION global variable is used. the $_COOKIE global variable is used.
The DOCTYPE declaration above contains a reference to a DTD file. The purpose of a DTD is to define
the structure and the legal elements and attributes of an XML document:
The DTD above is interpreted like this:
● !DOCTYPE note - Defines that the root element of the document is note
● !ELEMENT note - Defines that the note element must contain the elements: "to, from,
heading, body"
● !ELEMENT to - Defines the to element to be of type "#PCDATA"
● !ELEMENT from - Defines the from element to be of type "#PCDATA"
● !ELEMENT heading - Defines the heading element to be of type "#PCDATA"
● !ELEMENT body - Defines the body element to be of type "#PCDATA"
Module 6: React JS
So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a
JavaScript compiler/transpiler.
● It is faster than regular JavaScript because it performs optimization while translating the code to
JavaScript.
● Instead of separating technologies by putting markup and logic in separate files, React uses
components that contain both.
● It is type-safe, and most of the errors can be found at compilation time.
● It makes it easier to create templates.
Basic JSX
● Every JSX tag is converted to React.createElement call and its object representation.
● JSX Expressions, which are written inside curly brackets, allow only things that evaluate to some value like
string, number, array map method and so on.
● In React, we have to use className instead of class for adding classes to the HTML element
● undefined, null, and boolean are not displayed on the UI when used inside JSX.
Features of ReactJS
React is a JavaScript Library created by Facebook for creating dynamic and interactive applications and
building better UI/UX design for web and mobile applications. React is an open-source and
component-based front-end library. React is responsible for the UI design. React makes code easier to
debug by dividing them into components.
Features of React:
● JSX (JavaScript Syntax Extension) JSX is a combination of HTML and JavaScript. You can
embed JavaScript objects inside the HTML elements. JSX is not supported by the browsers, as a
result Babel compiler transpiles the code into JavaScript code. JSX makes codes easy and
understandable. It is easy to learn if you know HTML and JavaScript.
● Virtual DOM: DOM stands for Document Object Model. It is the most important part of the
web as it divides into modules and executes the code. Usually, JavaScript Frameworks updates
the whole DOM at once, which makes the web application slow. But react uses virtual DOM
which is an exact copy of real DOM. Whenever there is a modification in the web application, the
whole virtual DOM is updated first and finds the difference between real DOM and Virtual DOM.
Once it finds the difference, then DOM updates only the part that has changed recently and
everything remains the same.
● One-way data binding: ReactJS is designed in such a manner that follows unidirectional data
flow or one-way data binding. The benefits of one-way data binding give you better control
throughout the application. If the data flow is in another direction, then it requires additional
features. It is because components are supposed to be immutable and the data within them
cannot be changed. Flux is a pattern that helps to keep your data unidirectional. This makes the
application more flexible that leads to increased efficiency.
● Performance: ReactJS is known to be a great performer. This feature makes it much better
than other frameworks out there today. The reason behind this is that it manages a virtual DOM.
The DOM is a cross-platform and programming API which deals with HTML, XML or XHTML.
The DOM exists entirely in memory. Due to this, when we create a component, we did not write
directly to the DOM. Instead, we are writing virtual components that will turn into the DOM
leading to smoother and faster performance.
● Simplicity: ReactJS uses JSX file which makes the application simple to code as well as
understand. We know that ReactJS is a component-based approach which makes the code
reusable as you need. This makes it simple to use and learn.
Problems
Create a XML page storing name, country, runs scored, balls faced for three batsmen.
Represent the same data as a JSON object.
<team>
<player>
<type>batsman</type>
<name>Warszawski</name>
<country>Russia</country>
<runs>100</runs>
<balls>69</balls>
</player>
<player>
<type>batsman</type>
<name>Pandurang Butowski</name>
<country>Russia</country>
<runs>69</runs>
<balls>100</balls>
</player>
<player>
<type>batsman</type>
<name>Podborski </name>
<country>Japan</country>
<runs>234</runs>
<balls>20</balls>
</player>
</team>
{
"teamName": "Mumbai",
"members": [
{
"name": "Pobdorski",
"runs": 234,
"balls": 20,
"type": "batsman",
"country":”Japan”,
},
{
"name": "Pandurang Butowski",
"runs": 420,
"balls": 100,
"type": "batsman",
"country":”Russia”,
},
{
"name": "Warszawski",
"runs":100,
"balls": 69,
"type": "batsman",
"country":”Japan”,
}
]
}
Create a HTML, page showing a message “I use media query”. Write media query such
that the text color changes to light gray when browser window is 600px wide or less
and otherwise it is black.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>I use media query</h1>
</body>
</html>
CSS
@media (max-width: 600px) {
h1{
color: #808080;
}
}
Create a HTML form that accepts first name, last name, department and designation
from the user. Create a PHP code that stores this information in a mysql database
named employee with an existing table emp_details having appropriate schema and
acknowledges the user through appropriate message about success or failure during
data insertion. Assume suitable username and password to access database.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
<label>First name </label>
<input></input>
<br>
<label>Last name</label>
<input></input>
<br>
<label>Department</label>
<input></input>
<br>
<label>Designation</label>
<input></input>
<form>
</body>
</html>
Write JavaScript code to change background colour of the web page automatically after
every five seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js"></script>
</head>
<body id=”changeBg”>
<h1>Hello world</h1>
</body>
</html>
Script
let i = 0;
function changeBackground() {
let bg = document.getElementById("changeBg");
var colors = ["black", "blue", "red", "green", "brown"];
bg.style.backgroundColor = colors[i];
i = (i + 1) % colors.length;
}
setInterval(changeBackground, 5000);
Write an external stylesheet and link it with HTML code. The stylesheet should include
the following.
i. The web page will have the background image “img1.jpg”.
ii. The table headings will have red background color.
iii. Background color of alternate paragraphs are different.
iv. The hyperlinks on the web page will not have underline.
style.css
body {
background: url(“gf.png”);
}
th {
background: red;
}
p:nth-child(odd)
{
background:#333;
color: #fff;
padding: 5px;
}
p:nth-child(even)
{
background:#fff;
padding: 5px;
}
a {
Text-decoration: none;
}
Design a web page to maintain a Library Catalogue using XML. It should maintain the
name of the book, author, publisher, and year of publishing. Format it in the tabular
manner using XSLT.
Write code to process online Alumni information for your college. Create forms to get
name, address, date of birth, and email id. Use check boxes for taking hobbies and
radio buttons for selecting branches. Write JavaScript code to validate the following:
i. User has filled all the fields prior to form submission
ii. Valid email-id (with „@‟ and „.‟)
iii. Age validation using DOB (>=22 years)
<html>
<head>
<title> FormData</title>
<script src="script.js"></script>
</head>
<body>
<fieldset id="hobbies">
<legend>Choose your hobbies</legend>
<input name="reading" type="checkbox" id="reading" value="R"/>
<label for="reading">Reading</label><br>
<fieldset id="branch">
<legend>You belong to which branch ?</legend>
Script
function validate(DOB){
var twentytwo = momemt().subtract(22,"years");
var birthday = moment(DOB)
if(!birthday.isValid()){
return "invaliddate"
}
elseif(twentytwo.isAfter(DOB)){
return "greater than 22, you are good";
else{
return "Ops wait till 22";
}
}
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Create an HTML page which will divide a page in two horizontal fragments using
frameset tag, each frame should have different background color & different headings.
<!DOCTYPE html>
<html>
<head>
<title>HTML Target Frames</title>
</head>
<noframes>
<body>Your browser does not support frames.</body>
</noframes>
</frameset>
</html>
In the same directory there are upper.htm and lower.htm which are taken as source by frame tag.
</body>
</html>
<h1>This tag is deprecated so please don’t ask such questions and remove such outdated
things from the syllabus. थंक
ु ले तम
ु च्या अभ्यासक्रमावर.</h1>
</body>
</html>