Front
Front
2. Increased Productivity: Developers can leverage libraries to avoid reinventing the wheel,
allowing them to focus on the unique aspects of their project and accelerate development.
3. Consistency: Libraries are often designed with consistent interfaces and coding standards,
promoting uniformity in code structure and reducing the likelihood of errors.
4. Reliability: Since libraries are typically well-tested, using them can enhance the reliability of
your software. Bugs and issues are often discovered and resolved by a broader community of
developers.
5. Reduced Development Time: Developers can build on existing functionality without starting
from scratch, leading to faster development cycles.
6. Specialized Functionality: Libraries often provide specialized functions or algorithms that may
require significant expertise to develop. By using a library, developers can access these features
without having to implement them independently.
7. Community Support: Popular libraries often have active communities of developers, providing
support, documentation, and updates. This can be valuable for troubleshooting and staying up-
to-date with best practices.
8. Scalability: Libraries can help handle complex tasks and improve the scalability of a project by
providing optimized and efficient solutions to common problems.
9. Reduced Code Size: By using libraries, developers can reduce the overall size of their
codebase, making the software more maintainable and easier to manage.
1. Library:
- A library is a collection of pre-written code or routines that can be used by other programs.
- You call a library, and it provides functions or classes that you can use as needed.
- In a library, you have control over the flow of your application. The library is essentially a set
of tools that you can use, but you decide when and how to use them.
2. Framework:
- A framework is a more comprehensive architecture or platform that provides guidelines,
rules, and a structure for building software applications.
- When using a framework, the framework often dictates the flow of control. Your code fits
into the framework, and the framework decides when and how to invoke your code.
- Inversion of Control (IoC) is a key concept in frameworks, where the control flow is inverted –
instead of you controlling the flow, the framework controls the flow of your application.
In summary, while both libraries and frameworks provide reusable code, the key distinction is in
the control flow: you control the flow with a library, and the framework controls the flow with a
framework.
2. Structural Guidelines: Frameworks come with predefined structures and coding conventions,
promoting a standardized and organized approach to development. This helps maintain
consistency across the codebase.
4. Ease of Maintenance: With a consistent structure and modular design, frameworks make it
easier to maintain and update applications. Changes can be applied more uniformly, reducing
the risk of introducing errors.
5. Community Support: Popular frameworks often have large and active communities. This
community support provides access to documentation, forums, and a wealth of resources,
facilitating problem-solving and knowledge-sharing.
6. Scalability: Frameworks are designed to handle the growth of applications. They often
include features and practices that support scalability, making it easier to expand and adapt
applications as needed.
7. Security Features: Many frameworks come with built-in security features, helping developers
follow best practices and avoid common security pitfalls. This can contribute to the creation of
more secure applications.
8. Rapid Development: Frameworks streamline the development process by offering tools and
utilities that speed up common tasks. This results in faster development cycles and quicker
time-to-market for applications.
10. Inversion of Control (IoC): Frameworks often implement IoC, where the control flow is
inverted. This can simplify application development by allowing the framework to manage the
flow of execution.
In summary, frameworks provide a structured and efficient way to develop software, offering
benefits such as code reusability, productivity gains, maintenance ease, community support,
and features that contribute to security and scalability.
Software developers often use the words library and framework. Both contain reusable codes
that someone else has written, tested, and proven to be used.
What is a library?
A library is a prewritten set of codes that can be reused. Libraries give useful functions,
methods, or objects. You can use them in your application code. Whenever necessary you don't
need to rewrite the codes from scratch. You can just use the library to get used to the method.
Eg: There’s a method ‘findInverse(String)’ in a particular library. It will return the inverse of the
word that we give. We can straightway call this method in the library whenever we need an
inverse of a particular word. We do not need to write the whole logic behind this method
everywhere we need that functionality.
JavaScript libraries
JavaScript libraries are written in JavaScript. There are dozens of JavaScript libraries available.
Normally these libraries are focusing on some narrow scope.
First component is HTML. It prepares the structure of the web page. The second one is CSS. CSS
styles the structure by using stylings. The third one is JavaScript. JavaScript is responsible for
the Interactivity of the web page.
We have learned JavaScript libraries and frameworks during our last lesson. First, let us have a
look at the JavaScript libraries. We will be learning about jQuery which is a well-known and
commonly used JavaScript library.
What is jQuery?
jQuery Features
o DOM Manipulation: jQuery can be used to manipulate DOM elements using its
built-in functions.
o DOM Selection: jQuery provides selectors which can be used to retrieve DOM
elements. There are several selectors that we can use such as name, id, CSS class,
attribute name, etc.
o Cross-browser support: jQuery handles the cross-browser issue. The user does not
need to worry about it.
o HTML Event methods: jQuery has events like click, dblclick, blur, mouseenter, etc.
which are equivalent to DOM events.
o Ajax: jQuery includes AJAX functions to load data from servers without refreshing.
o Special Effects: Special effects like show, hide, fade-in, fade-out, animations can be
applied to DOM elements.
With these features of jQuery, there are so many advantages that can be obtained from jQuery.
Advantages of jQuery
o Easy to learn
o Cross-browser support
o Unobtrusive
We learned that jQuery is a JavaScript library. To use jQuery in our HTML, we have to have a
reference to the jQuery library in our HTML file.
You can directly download the jQuery library and include it in HTML file. Then you can use
jQuery in offline mode. You don't need the internet to work with jQuery.
o Use the jQuery official website (you can refer to Link1 given below) to download the
jQuery library.
o You can download either compressed or uncompressed versions
according to your requirement (Figure 1).
o After downloading, move the jQuery library into the folder where your HTML file
lies. (You also can place it in a different location)
o Include jQuery into the HTML file. You can use the following syntax to include
jQuery. Make sure you include inside <head> tag. (If you are storing the jQuery file in
a different location, specify the path)
Tip: Do you know why we include jQuery inside the <head> tag? That’s because we must load
the jQuery before anything else in the website loads.
Instead of using the above offline method, you also can get the reference to the jQuery library
from public CDN (Content Delivery Network) such as Google, Microsoft, CDNJS, etc.
Content Delivery Network distributes the content from the original server throughout the world
by caching the content.
o Use the jQuery official website and scroll it down the way till you find the CDN
section. You can find some of the available CDNs (Figure 2).
o Copy the code snippet and place it inside the <script> tag inside the header section
as shown below.
Link1: [Link]
Activity 2
In the following example, we have used the jQuery hosted by Google. When you click on ‘hide’
button. It will hide the paragraph. If you click on ‘show’ button it will show the content.
Now include jQuery from another CDN (eg: Microsoft,CDNJS, etc.) and check whether it’s
functioning well.
Note: If you cannot see the preview in the code playground, click on the 'Both' option at the
right bottom panel. At present, you may see your JavaScript file (e.g., [Link]). To open the
HTML file (e.g., [Link]), you can hover on the right edge of the light black pane (See Figure
3) and drag it to the right as shown with the [Link] you can see a list of files as shown in
Figure 4. If you need the [Link] file, click and open it.
Figure 3 Figure 4
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="[Link]
</head>
<body>
<!-- Include jQuery from Google CDN -->
<button id="hideBtn">Hide</button>
<button id="showBtn">Show</button>
<p>This is a paragraph to hide/show.</p>
<script>
$(document).ready(function () {
$("#hideBtn").click(function () {
$("p").hide();
});
$("#showBtn").click(function () {
$("p").show();
});
});
</script>
</body>
</html>
jQuery Syntax
Now let us have a look at how to define standard jQuery syntax to load and perform actions on
HTML elements.
jQuery Syntax
A typical jQuery syntax starts with a dollar sign ($) sign and ends with a semicolon (;).
$(selector). action ()
2. selector – Represent the HTML element and used it to find the HTML element that
manipulation needs to be done.
Normally, JavaScript is written inside the script tags and as a practice, we include them just
before the end of the body section of an HTML file. Can you think about the reason for that?
HTML loads from top to bottom. In an HTML page, HTML needs to load first before starting to
work with them. If not, the actions may fail.
Example:
Therefore, when you are writing JavaScript, you must be aware of this.
jQuery Selectors
You already know the basic syntax of jQuery. In basic syntax, after you access jQuery, you have
to select the HTML element that you need to perform some action. Selecting the HTML element
or the DOM element is done by using selectors.
jQuery Selectors
jQuery selectors enable to find DOM elements in the web pages. Usually jQuery selector starts
with $(). Inside the (), the selector parameter is specified. Selector parameter specifies a
pattern to match the HTML elements. jQuery uses CSS selector patterns.
You can use the element name to select the HTML element.
e.g.
Select Elements by Id
Id is a unique identifier. You can use the Id attribute of an HTML tag to find a specific element in
a document. It is specified in jQuery starting with ‘#’ symbol.
e.g.
Look at the following code snippet. As you can see, if you select the elements by the id
‘myPara1’, it will return the element with Id = ‘myPara1’.
jQuery enables to find elements based on attributes set on it. You can specify attribute name
on square brackets.
e.g.
o $(‘[class = “myclass”]’) will return the elements with class attribute ‘myclass’.
Look at the following code snippet. As you can see, if you select the elements by title =
“myTitle”, it will return the elements with title attribute = ‘myTitle. If $(‘[class = “myCls”]’), then
it will return all the elements which have a class attribute with 'myCls' as a value.
jQuery provides quite a lot of ways to find HTML elements. A few of them are mentioned below
in Table 1.
Table 1: jQuery Selectors
jQuery Events
We already know how jQuery can be used to find the DOM elements. Now let us see how we
can use the jQuery library to catch the changes of DOM elements and respond to them.
What is an Event?
Recall the instances where you visit several websites. What are the things that you perform
there? You may click on buttons, scroll up and down, enter details through the keyboard and
there can be many more. An event is an action that happens in the system which lets your
system know that it can react to that. When you click on a submit button in a form, the system
will react to that by submitting your form, which may be giving an alert message or some other
response.
When an action takes place, an event triggers and notifies the event handler to handle the
raised event (Figure 1). The event handler is responsible to handle the events. Following are
some more examples of events.
o A mouse click.
o Document loading.
Now let us see what jQuery has facilitated for the events.
jQuery library provides methods to handle DOM events. These methods can be categorized into
several types for ease of study as mentioned below.
o Mouse events:
o click
o dblclick
o hover
o mouseenter
o mouseleave
o Keyboard events:
o keyup
o keydown
o keypress
o Form events:
o submit
o change
o blur
o focus
o Document/Browser events:
o load
o unload
o scroll
o resize
o ready
Now we know jQuery provides methods to catch the events. Let’s now see how this triggered
event is handled.
Event Handling
To handle the DOM events using jQuery methods, first, we need to select the DOM element(s).
For that, we can use jQuery selectors. Then invoke the appropriate event method provided by
jQuery.
We have already learned this before. You can recap how we have applied this in previous
lessons.
Inside the jQuery method, you can specify the handler/callback function. You can specify the
response you need to perform inside this function.
On method
On method takes two arguments. The first one is the event name and the second one is the
event handler name. When an event occurs, the handler function executes.
Look at the following example. When the element with id = ‘#pId' is clicked, the handler
executes and hides the element.
‘this’ keyword in an event handler represents a DOM element that raised an event. In the above
example, 'this' refers to the DOM element with id 'pId’.
Activity 1
Have a look on how mousenter event has been handled using jQuery. Write the necessary
jQuery code segment to hide the ‘Click Me’ button when you click on it using on method.
Answer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hide Button Example</title>
<script src="[Link]
</head>
<body>
<script>
$(document).ready(function() {
// Using on method to handle mouseenter event
$('#clickMeButton').on('mouseenter', function() {
// Hide the button when it is clicked
$(this).hide();
});
});
</script>
</body>
</html>
Output
Suppose you want to trigger the same event whenever two actions happen.
e.g., mouse enter or leave the paragraph elements. You can specify as shown below.
e.g., Suppose you need to have different event handlers for the mouse enter and mouse leave,
then you can specify it as shown below.
Sometimes you may need to perform the same handler operation in different places. Then you
can write your own named function and use the name (name without ()) of it inside the on
method as the second argument. In the below example, we can consider clicked as a named
function.
e.g.
jQuery Effects
We have learned how to use jQuery events to handle DOM elements and make the web
applications interactive. Now let’s see how we can make the web application more attractive.
jQuery Effects
We can create the contents of a web application using HTML and beatify it using CSS. jQuery
effect can be used to create visual effects and make it more attractive. jQuery provides several
methods to create effects on DOM elements.
[Link] Effects
There are three commonly used methods available to control the display effects of
elements(See Figure 1).
o show() –
o Display the hidden selected elements.
Note: This method restore the CSS style property ‘display:none’ to initial value to
display the selected element
o hide() –
o Hide the selected element.
Note: This method simply sets the CSS style property ‘display: none’ for the selected
elements.
o toggle() –
oShow or hide the elements in such a way that if the element is initially
displayed, it will be hidden; if hidden, it will be displayed.
General syntax: $ ( Selector ). effect(speed, callback);
where,
Speed (Optional) – Specifies the speed of the effect. Possible values are “slow", "fast",
or milliseconds.
There are few methods provided by jQuery to display or hide the HTML elements by gradually
increasing or decreasing their opacity (See Figure 2).
o fadeIn() -
Where,
Speed (Optional) – Specifies the speed of the effect. Possible values are "slow", "fast", or
milliseconds.
o fadeTo() -
o Similar to the fadeIn() method, but it lets you fade in the elements to a
certain opacity level.
o Requires the opacity that specifies the final opacity of the target element.
Speed (Optional) – Specifies the speed of the effect. Possible values are "slow", "fast",
or milliseconds.
3. Sliding Effects:
There are few sliding methods provided by jQuery to hide or show the HTML elements by
gradually decreasing or increasing their height (See Figure 3).
o slideDown()
Where,
Speed (Optional) – Specifies the speed of the effect. Possible values are “slow", "fast",
or milliseconds.
o animate()
o Used to create custom animations
Note: Typically use numeric CSS properties. Not all the CSS properties can be
animatable.
Where,
Speed (Optional) – Specifies the speed of the effect. Possible values are “slow", "fast",
or milliseconds.
You have learned some jQuery effects. Now you know how to apply those jQuery effects and
make visual effects in your website.
Let us see another very important feature in jQuery which will be very useful when you are
working with jQuery.
jQuery chaining allows us to perform multiple action on the same set of elements, all within a
single line of code(See 'Reset and FadeOut' button behaviour in Figure 4). This will make your
code more concise, readable and helps to increase the performance. Think how can we
increase performance by using method chaining? Look at the general syntax and see how you
can write multiple methods for a single element.
You have learned quit a lot of ways to make your web application attractive. Now let’s try
another activity and get familiar with method chaining.
If you're developing a website and require user input, you can utilize web forms. Assume you
are designing a simple user registration form that will collect the user's full name, age, address,
phone numbers, and email address. For example, users may enter their age in digits or as text,
which would be extremely difficult to use afterwards. Furthermore, they may not enter data
into some of the form's most critical data fields. To avoid this, we must validate the user input.
Let's start with form validation and then learn how to use jQuery for HTML form validation.
Form validation is a process of confirming the relevant information entered by the user in the
input field. When you include forms on your website for user inputs, it is always advisable to
perform some validation on the data entered. This not only ensures that your application
receives the type of data it can work with, but it also makes for a good user experience as users
will be able to be warned of the incorrect input and be given hints of the kind of data that is
acceptable.
There are many ways to do the form validation using jQuery. One method is to validate a form’s
data by writing the validation rules from scratch. It is similar to the JavaScript form validation;
there you have to create an HTML file that consists of a form with several input fields and
includes the JavaScript file having jQuery code for form validation.
The next method is using the inbuilt jQuery validation plugin. A plugin is a piece of code written
in a standard JavaScript file. These files provide useful jQuery methods which can be used along
with jQuery library methods. There are plenty of jQuery plugins available that you can
download.
To use methods available in a plugin, we include a plugin file very similar to a jQuery library file
in the <head> section of the HTML file . We must ensure that it appears after the main jQuery
source file, and before our custom JavaScript code.
Now, let’s see how we can add jQuery validations to an HTML form we have created.
Adding jQuery Validations to an HTML Form
Following is the HTML registration form (Figure 1) that has been created to get the details from
the user. As you can observe, there are no validations included before the submission button.
So, even if all of the input fields are empty, or if we enter invalid user input (for example, an
email address without a @), we may still submit the form.
Following is the CSS file (Figure 2) that add styles to the HTML form that have been created
above in Figure 1.
Next, we will see what are the validations that we going to add to this form.
There are no hard and fast rules on what we should validate before submitting the form. It can
be decided according to your requirement.
According to this example, the following conditions are used to validate the user input before
submitting the form.
The link to the JavaScript file related to jQuery validations of HTML forms is included in the
<head> section of the HTML file as shown in Figure 4.
Figure 4: Link JavaScript file to the HTML document
A function is written in the JavaScript file to validate the inputs (Figure 5). The function
initializes form validation on the registration form. It takes the name attribute "registration"
and specify the validation rules with the 'rules:' keyword as shown below.
Here, the name is a required field. Then, the email is also required as well as it is also specified
that email should be validated whether it contains the format of an email by the built-in "email"
rule. So, when you have more than one rule to be included, you can use curly brackets ({}).
Within that, you can include multiple rules.
Password and confirm password are required fields, it should contain a minimum length of five
and the "equalTo" attribute is used to check whether the confirm password field is equal to the
password.
Validation error messages specify with the 'messages:' keyword. For each rule that we added
previously, we have to specify an appropriate error message that should be displayed. We have
written an appropriate message for each attribute.
Further Reading
jQuery Validations
Following we have embedded StackBlitz which is an online IDE where you can use it to
complete your Activity 1, Activity 2 and Activity 03.
Activity 1
In the HTML form, add a new input field named ‘telenumber’ to get the telephone number
from the user.
Then, add validation rules to the JavaScript file to make ‘telenumber’ a required field and only
10 numbers will be accepted.
In the JavaScript file, include appropriate messages to be displayed for the validation rules that
you have used.
Activity 2
In the same HTML form, add a new input field named ‘dateofbirth’ to get the date of birth from
the user.
Hint: you may use a ‘datepicker’
Then, add suitable validation rules to the JavaScript file to make ‘dateofbirth’ a required field
and only date format inputs will be accepted.
In the JavaScript file, include appropriate messages to be displayed for the validations rules that
you have used.
Activity 3
In the same HTML form, add a new input field named ‘gender’ to get the gender as male or
female from the user.
Hint: you may use a ‘radio button’
Then, add validation rules to the JavaScript file to make ‘gender’ a required field and include an
appropriate message to be displayed for the validations rule that you have used.
Answer
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
<!-- Include jQuery and jQuery UI for datepicker -->
<link rel="stylesheet" href="//[Link]/ui/1.12.1/themes/base/[Link]">
<script src="[Link]
<script src="[Link]
<!-- Include your custom JavaScript file -->
<script src="[Link]"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
form {
max-width: 400px;
margin: 0 auto;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"],
input[type="radio"] {
margin-bottom: 10px;
padding: 8px;
width: 100%;
box-sizing: border-box;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
}
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<input type="submit" value="Submit">
</form>
</body>
</html>
[Link]
$(document).ready(function () {
$("#myForm").submit(function (event) {
// Clear previous error messages
clearErrors();
// Validate gender
var gender = $("input[name='gender']:checked").val();
if (!gender) {
displayError("#male", "Please select your gender.");
[Link]();
}
});
Output
Other than what we have learnt, there are some simple ways (with less code) that we can do
form validations. Let’s see how we can do that.
Unobtrusive Validation
In unobtrusive validation, without writing a lot of validation code, you can perform simple
validation by adding suitable attributes. Firstly, we need to add the following libraries to the
script tag in the <head> section of the HTML
file, [Link] and [Link].
These libraries provide a list of data attributes (data-val, data-val-required, and many more) for
validation. Then the form should be built according to the requirements in which different
types of data attributes can be used. Some of the attributes that can be used to specify the
required fields, email address, maximum length and minimum length of an input field are
mentioned below. We can use these attributes within the input fields to validate each input
according to our validation rules.
Required
data-val-required=“This is required.”
data-val=“true/false”
EmailAddress
data-val-email=“Error message”
MaxLength
data-val-maxlength=“Error message”
MinLength
data-val-minlength=“Error message”
To add unobtrusive validation to an HTML form, first, you should add related libraries and
plugins into the <head> section of the HTML. You can search for it and get the links of the
respective libraries.
In this HTML file in Figure 6, for each input field, we are using data-val-required and data-val
attributes to do the validation. data-val-required is used to specify the message for each rule
and data-val is used to add rules to the input elements. <span> tag is used to display the
relevant message of each input field.
What is Asynchronous?
The meaning of asynchronous is not simultaneous or not occurring at the same time, and
relating to computer applications, asynchronous means that an event can occur independently
without waiting for another event.
In programming, synchronous operations are carried out one task at a time. When one task is
completed, the next step begins. In the Figure 1, it displays how synchronous and asynchronous
approaches works.
Synchronous approach
o Carries one task at a time and waits until previous task is completed.
o Synchronous calls are suitable when it is necessary to execute tasks in a sequence
and when it does not require much time for execution.
Asynchronous approach
The following example explains the difference between sychronous and asynchronous
approaches.
Example: Consider a button that shows more information about web page content when it
clicks.
Classic web applications use the synchronous approach, which is the opposite of asynchronous.
In the synchronous approach, after clicking the button, the web page waits until the
information is received from the server. When the response is received, the web page reloads
and shows information. One task happens after another. Until the response is received, the
user cannot interact with any other page elements.
However, in the asynchronous approach, the website keeps functioning without waiting for a
response from the server. When a response is received from the server, information will display
on the web page. Users can interact with other elements on the web page and work with them
without waiting for a response.
What is AJAX?
AJAX is not a programming language but a set of web development techniques that use various
web technologies on the client-side to create better, faster, and more interactive web
applications.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data
with the server. This means that it is possible to update parts of a web page without reloading
the whole page.
This method is extremely useful for website performance and usability because the user can
see certain information generated without reloading the page.
Advantages of AJAX
AJAX uses a different approach to retrieve data from the server comparing with traditional
approach. Let’s learn how the browser requests the webserver to get some information from
the server in conventional and AJAX methods.
How does AJAX work?
o The browser sends an HTTP request to the webserver and waits until a response is received
from the server.
o The request is sent to the web-server, and the server process the request.
o The browser performs a JavaScript call to the Ajax engine. In that process, an
XMLHttpRequest object is created by the AJAX engine.
XMLHttpRequest (XHR) objects are used to interact with servers. This enables a Web page to
update just part of a page without disrupting what the user is doing. (You can find more
Information about XMLHttpRequest in the additional information section.)
o The server interacts with the database and retrieves the data.
o HTML, XML, or JavaScript data is returned to the AJAX engine, which then delivers the
requested data to the browser.
Figure 3: Steps of AJAX approach (Zhao, 2006)
In this method, data will be displayed on the browser without reloading the whole page.
Activity
Identify how AJAX displays information without reloading the browser by navigating different
websites such as Google Map and Netflix.
Answer
AJAX (Asynchronous JavaScript and XML) enables dynamic content updates on a web page
without the need to reload the entire page. This is achieved by making asynchronous requests
to the server, retrieving data, and updating specific parts of the page dynamically. Here's how
AJAX displays information without reloading the browser, as observed in websites like Google
Maps and Netflix:
1. Google Maps:
- Interactive Maps: Google Maps uses AJAX to load and update maps dynamically. As users
interact with the map, such as zooming in or panning, AJAX requests are made to retrieve new
map tiles and information without refreshing the entire page.
- Autocomplete Suggestions: When you start typing in the search bar, AJAX is often used to
fetch autocomplete suggestions in real-time, providing a responsive and dynamic user
experience.
2. Netflix:
- Content Streaming: Netflix utilizes AJAX to dynamically load and update content on its
streaming platform. When users navigate through the interface, select a video, or seek within a
video, AJAX requests are made to fetch and display the relevant information without reloading
the entire page.
- User Ratings and Recommendations: User interactions, such as rating a show or receiving
personalized recommendations, trigger AJAX requests to update the user interface with new
information dynamically.
In both cases, AJAX requests are initiated by client-side JavaScript code. These requests are
typically asynchronous, allowing the rest of the page to remain responsive while data is fetched
in the background. The retrieved data, often in JSON format, is then used to update specific
elements on the page without requiring a full page reload.
This approach enhances the user experience by providing seamless and interactive content
updates, reducing the need for page refreshes and improving the overall performance of web
applications.
Additional Information
[Link]/xml/xml_http.asp
References
[Link]
Zhao, B., Huang, X. and Wu, G., 2006, October. OGC Web services based on Ajax engine. In
Geoinformatics 2006: Geospatial Information Technology (Vol. 6421, pp. 222-232). SPIE.
Getting Started with AJAX using jQuery
In the previous lesson, you have learned what AJAX is and why it is important. During this
lesson, you will get to know how to use AJAX with jQuery and the mostly used jQuery AJAX
methods and their usages.
AJAX calls can be made with raw JavaScript, but this can be challenging since different browsers
have different AJAX implementation syntaxes.
Writing regular ajax calls might become tedious when a web application uses multiple forms of
Ajax calls, such as both synchronous and asynchronous calls, or different response formats,
such as string messages, HTML, XML, and JSON.
However, if you combine jQuery and AJAX, you can leverage AJAX with minimal effort. If you
use jQuery, you can create AJAX functionality with just one line of code.
You should have a better understanding of HTTP methods and API calls when you are using
these AJAX methods. So, let’s discuss HTTP methods and see what is an API call is.
HTTP Methods
The Hypertext Transfer Protocol (HTTP) is designed for clients and servers to communicate with
each other. HTTP is a request-response protocol that communicates between a client and a
server. A client (browser) sends an HTTP request to the server, and then the response is sent by
the server to the client. The response may include the requested content as well as status
information about the request.
POST, GET, PUT, PATCH, and DELETE is the most used HTTP methods.
API stands for “Application Programming Interfaces. They allow different applications to
communicate with one another and exchange data among them.
For example, when you are logging into a website, you need to provide a username and
password. When you enter your information in the login interface, data is sent to the server for
verification through an API call.
Mobile applications display real-time data such as weather data and game scores by fetching
information from available APIs. Such manner nowadays in each and every web application use
APIs for developing web applications and mobile apps.
You'll need the Uniform Resource Identifier (URI) of the server or external program whose data
you want to access in order to make an API request. You won't know where to send your
request if you don't have this.
A Uniform Resource Identifier (URI) is a character sequence that identifies a logical (abstract) or
physical resource that is connected to the internet. A URI is a unique identifier for a resource.
Once you have the URI, then you need to know how to formulate the request.
The first thing you need to include is a request verb. The four most basic request verbs are:
GET, POST, PUT, DELETE.
The following example shows a GET API call and how it responds. When a GET request is made
server sends a response in JSON or XML format with an HTTP response code of 200 (OK) if the
resource is available. If that resource doesn’t exist, then it will send back the HTTP response
code 404 (not found).
JSON
o JSON stands for JavaScript Object Notation. It is a lightweight text-based open standard
designed for human-readable data interchange. Data is represented in name/value pairs as
follows.
{ “name”: “Malsha”,
“subject”: “Maths”,
“mark”: 80 }
o Objects are held in curly braces, and each name is followed by a ':' (colon), with name/value
pairs separated by (comma).
o In the above example, name, subject and, mark are the properties of this object.
o If you parse the JSON string with a JavaScript program, you can access the data as an object.
let personName = [Link];
You can find more Information about JSON in additional readings section.
Now let’s try a third-party, public API to get an understanding of how API works. This GET
request is requesting user information of one particular person. As the response, data in JSON
format is received. It includes the user information of one particular user.
In this lesson, we use public third-party APIs, which are freely available to access.
jQuery provides several methods for AJAX functionality. The following are some of the most
significant jQuery AJAX methods.
o load() - send HTTP requests to load the HTML or text content from the server and add them
into the HTML element.
o get() – sends HTTP GET request to load the data from the server.
o post() – send HTTP POST request to load or submit data to the server.
o getScript() - send an HTTP GET request to load the JavaScript file from the server and then
execute it.
o getJSON() - send HTTP GET requests to load JSON encoded data from the server.
The following sections describe ajax() and load() methods, while the get() and post() methods
will be covered in the next lesson.
Now let’s understand how to use the ajax() method in different web applications.
ajax() Method
The ajax() method in jQuery provides the core functionality of AJAX. It communicates with the
server through asynchronous HTTP requests. The syntax of the ajax() method is shown in the
following.
$.ajax(url,[options]);
o Options: This parameter is optional and mentions configuration options for Ajax requests. An
options parameter can be specified using JSON format.
Example 1:
Now let’s discuss a simple code example to use the ajax() method to retrieve data from an
HTML file. Here, more information should appear when the user clicks the “click here” button,
as shown in Figure 2.
[Link] file (Figure 3) contains the HTML code, which should be displayed when the button
is clicked.
Example 2:
The ajax() method is used to retrieve data from the server via an AJAX request. Now let’s try
another example where the ajax() method retrieves data using a GET HTTP request.
In this example, as the first parameter, we need to mention an URL from which we want to
retrieve the data. As for that, a public GET API is used as an URL to retrieve the data. You can
find more details about this API in additional readings.
load() Method
The load() method allows HTML or text content to be loaded from a server and added into an
HTML DOM element. The syntax of load() methods is as follows.
$(selector).load(URL,[data],[callback]);
The optional callback parameter specifies a callback function when the load() method is
completed. The callback function can have different parameters as follows.
Now let’s discuss a simple code example to use the load() method. When the web page loads,
data from an external text file is loaded to the web page. (Figure 5) The external file is named
[Link], and its content is shown in Figure 6.
The load() method can be written as shown in Figure 7 in the [Link] file, to display the
retrieved data from an external file without reloading the web page.
Now let’s discuss how to use the callback function for this task.
Callback Function
We could display an error message if external data did not retrieve successfully and a successful
message if content displays without an error. We can perform this task using the callback
function.
In the callback function, we mention three parameters: responseTxt, statusTxt, and xhr. Figure
8 shows how the callback function is implemented for this use case.
Figure 8: Callback function
If content retrieves successfully, the following alert box will be displayed first. After clicking the
ok button, the content will be loaded to the web page (Figure 9).
Now let’s see what will happen if an error occurs. Then the following error message will appear
(Figure 10).
Important: To execute web applications that use AJAX, web application needs to run on a
server. Because Ajax only works on a server. You can use a local server like XAMPP on your
computer. Otherwise, if you are using VSCode IDE, there is an extension called “live server”.
Activity 1
Navigate to the following sites and understand how an API works. Change the parameters of
following URLs and get different responses.
Example: Change the value of "country" parameter in first API and see the output. In the
second API, change the drilldowns parameter value to "State".
[Link]
[Link]
Activity 2
Read and identify the differences between available jQuery AJAX methods. Hint:
[Link]
Additional Readings
[Link]
More In formation on getJSON():
[Link]
[Link]
[Link]
[Link]
[Link]
You learned about AJAX in earlier lessons. When working with web applications, you will need
to use HTTP methods to perform a desired action on the server's resources. For example, to get
some required data from the server to the frontend you will be using a HTTP method.
As mentioned earlier, there are several HTTP methods that we can use when developing a web
application. GET, POST, PUT, HEAD, and DELETE are some of the most regularly used HTTP
methods. These methods relate to the operations create, read, update, and delete (or CRUD)
resources on the server.
o GET - Get the resource specified in the requested URL. URL may refer to a data-
handling process.
o POST - Send entities (specified in the entity body) to a data-handling process at the
requested URL.
o HEAD - Asks server to leave requested content out of response but send the rest of
the response.
o PUT - Update a resource at the requested URL with the new entity specified in the
entity body.
Figure 1 shows how the HTTP requests are sent through the network from Browser to the
Server. For an event (e.g., a button click) that has occurred on the client side (browser) will be
sent as HTTP request to the server. The backend server process the HTTP request and reply the
response to the client browser.
(Source: [Link]
jQuery offers many AJAX related methods to create AJAX requests. One of the core method is
$.ajax() (You have learnt about $.ajax() in previous lesson). $.ajax() offers more configuration
options to have the full control over the ajax request.
Let’s see how we can use $.ajax() method to create GET and POST requests.
You can simply specify the request type as ‘GET’ to create a GET request using $.ajax() method
as shown below. You can configure the rest of the parameters as required.
You can simply specify the request type as ‘POST’ to create a POST request using $.ajax()
method as shown below. You can configure the rest of the parameters as required.
jQuery also provides convenience methods to perform Ajax Request. But they are note
configurable as $.ajax() method.
Now let’s have a look at the convenience methods provided by jQuery to perform GET and
POST request.
If you do not care much about the error handling and configurability, you can use get() and
post() methods provided by jQuery to create AJAX requests. $.get() and $.post() are simple
methods that can be used to send and retrieve data asynchronously from a web server. The
major difference in between these two methods is that $.get() makes the request using HTTP
GET method whereas $.post() makes it using HTTP POST method.
General sysntax :
$.method(URL,data,success);
Where,
Data (optional) – a set of query string that is sent to the web server along with the request.
Normally specifies as key/value pairs.
Activity 1
Refer to the jQuery documentation (Refer link 1) and read the $.ajax() method. Try to figure out
the difference between the $.ajax() method and the convenience methods.
Answer
The `$.ajax()` method in jQuery is a general-purpose function for making AJAX requests, and it
provides a high level of flexibility and customization. On the other hand, the convenience
methods (`$.get()`, `$.post()`, `$.getJSON()`, etc.) are shorthand methods that simplify common
use cases.
- `$.ajax()` is highly flexible and allows you to set various options, such as `type`, `url`, `data`,
`success`, `error`, `beforeSend`, `complete`, etc.
- Convenience methods are more concise and provide a simpler interface. They have
predefined defaults for certain options, and you don't have to specify them unless you need to
override the defaults.
- In `$.ajax()`, you must explicitly specify the request type (GET, POST, etc.). If not specified, it
defaults to GET.
- Convenience methods have a default request type associated with them. For example,
`$.get()` defaults to GET, and `$.post()` defaults to POST.
- With `$.ajax()`, you need to explicitly set the `dataType` option if you want to specify the
type of data expected in the response (e.g., "json", "xml", "html").
- Convenience methods like `$.getJSON()` automatically set the `dataType` to "json," making it
simpler for handling JSON responses.
4. Shorthand Syntax:
- Convenience methods have a shorthand syntax that is easier to use for simple requests.
They automatically handle certain aspects of the request, such as the request type and data
serialization.
$.ajax({
type: "GET",
url: "[Link]/api",
data: { key: "value" },
success: function(response) {
// handle success
},
error: function(error) {
// handle error
}
});
Equivalent example using `$.get()`:
separateFunction([2,3,5,6,1])
$.get("[Link]/api", { key: "value" }, function(response) {
// handle success
});
In summary, `$.ajax()` is more powerful and customizable, while convenience methods are
designed for simplicity in common scenarios. The choice between them depends on the level of
control and customization you need for your AJAX requests.
In below example, you can see how $.get() method has been used to make AJAX request to the
“[Link]” file using HTTP GET method. It will retrieve the some information returned from the
server and display it in the browser without refreshing the web page.
POST request is very similar to GET request. In the below example, you can see how $.post()
method has been used to make AJAX request to send large amount of data to “[Link]” file
using POST method. The returned information from the server is displayed in the browser.
Activity 2
We have used AJAX get() method to retrieve Covid-19 data. Play around with the code and look
how get() method has been used. Also have a look on how retrieved data has been displayed in
the web page.
Note that this code has displayed only a few data among the data which sent by the server.
Now you need to display the ‘global_total_cases’ in the web page. (Hint: Open up the console
and expand the data object sent by server. You can see the whole set of data sent by the
server).
Link 1 : [Link]
Answer
It seems like you have a JavaScript code that uses the `$.get()` method to retrieve COVID-19 data and you
want to modify it to display the 'global_total_cases' on the web page. Since I don't have the specific code
you're referring to, I'll provide you with a generic example of how you might modify the code.
$(document).ready(function() {
// Make an AJAX GET request
$.get("[Link] function(data) {
// Log the data to the console
[Link](data);
In this example, the code sends a GET request to "[Link] using `$.get()`.
The retrieved data is logged to the console, and the 'global_total_cases' is extracted and displayed on
the webpage within an element with the id "totalCases."
Make sure to replace the API URL ("[Link] with the actual URL you are
using in your code.
Remember to check the structure of the data returned by the server by examining the console. You
might need to adjust the property names based on the actual structure of the returned data.
Single page applications (SPAs) vs Multi page applications (MPAs)
There are two web application development approaches as SPA and MPA. If you are creating a
web application, you will choose one of these approaches. As students learning web application
development, it is critical that you understand these approaches and choose the best one for
your work.
Let us consider Multi page application first, as it is a more traditional approach to web
development.
MPA
It requires a page reload every time the content changes. Each new request would be sent to
the server, and as a response, a new page would be sent back from the server (see Figure 1).
For an instance, when you click a button or a link, you will be going to new page.
For example, if you are going for a dinner with group of friends, you may ask for a menu and
order different food one by one. First you may get a drink, after that you will go through the
menu again and order rice and curry. When you order food, you get it one at a time from the
kitchen. With the multi page approach, you can get different pages from the server one at a
time.
It is more suitable for e-commerce sites, learning management systems like Moodle where you
have lot content and options to select.
- [Link]
- [Link]
- [Link]
Next, let’s consider about SPA approach.
SPA
A single page is a more modern approach to web development. It does not require page
reloading during use (Fig 2). As can be seen in Fig 2, when you click different links, part of the
page is re-rendered, rather than fetching a new page as in MPA. It works inside a browser. That
is, only one page will be fetched from the server, and no more pages will be fetched from the
server after that. Also, when you click something, it will only change part of the page.
Let us consider the previous example again. Rather than ordering food one at a time, you can
get your food from a buffet. You will get access to drinks, main dishes, and deserts all at once.
You do not need to go through a menu and order food one by one. Similarly, in a SPA, the
server loads the whole page, and you get all the data loaded automatically.
Certainly, let's categorize the mentioned web applications into Single Page Application (SPA)
and Multiple Page Application (MPA).
- Google Maps
- [Link]
Explanation:
- SPAs like Facebook and Google Maps dynamically update content without full-page reloads,
providing a seamless user experience.
- MPAs like [Link], [Link], and [Link] generally load new pages from the server
when navigating between different sections or content.
Let us do the activities listed below.
Activity 1
Identify ten websites that you visited in the last month. You may have visited Facebook, Daraz,
[Link], and many news websites, for example.
Determine whether they use the SPA or MPA strategy in web development based on the
concepts you learned during the lesson.
Answer
While I don't have access to your specific browsing history, I can provide general information
about the likely strategies employed by some of the websites you mentioned based on
common industry practices:
1. Facebook:- Facebook primarily uses a SPA (Single Page Application) strategy. When you
navigate within the platform, the page content updates dynamically without full page reloads.
2. Daraz:- Daraz might use an MPA (Multiple Page Application) strategy. E-commerce websites
often adopt a multi-page approach, with distinct pages for product listings, product details, and
checkout.
3. [Link]:- Similar to Daraz, [Link] is likely to use an MPA strategy due to the nature of its
classifieds platform.
4. YouTube:- YouTube predominantly employs a SPA strategy. The video playback and user
interactions occur on a single page without requiring full page reloads.
5. WhatsApp:- WhatsApp, especially the web version, may use a SPA strategy to provide a
seamless and responsive messaging experience.
6. Instagram:- Instagram is likely to use a SPA strategy, enabling smooth and fast navigation
between different sections of the platform.
7. Twitter:- Twitter adopts a SPA strategy, allowing users to navigate between tweets,
notifications, and other sections without full page reloads.
[Link] Eats:- Uber Eats may use a mix of SPA and MPA strategies. The restaurant listings and
menus could be part of a SPA, while the checkout process might involve multiple pages.
9. Uber:- Uber's main application might use a SPA strategy for features like ride tracking and
account management.
Activity 2
Choose two websites (from Activity 1) that has used the SPA and MPA approach, and
investigate the types of resources you have downloaded each time you click on a link.
Hint: Open the Developer tools and navigate to the Network tab.
Answer
While I cannot directly access real-time data or inspect network requests for specific websites, I
can provide a general overview of the types of resources that are typically downloaded when
interacting with Single Page Applications (SPA) like Facebook and Multiple Page Applications
(MPA) like YouTube.
1. HTML: The initial HTML document is loaded when you first visit Facebook. Subsequent
interactions often involve dynamic updates to the DOM (Document Object Model) without full
page reloads.
2. JavaScript (JS): Facebook heavily relies on JavaScript to handle dynamic content updates, user
interactions, and asynchronous requests.
3. CSS (Stylesheets): Stylesheets are downloaded to ensure the proper styling and layout of the
content.
4. Images: Profile pictures, post images, and other graphical elements are downloaded as
needed.
5. API Requests: AJAX requests to Facebook's APIs are made to fetch and update data without
reloading the entire page. These responses are often in JSON format.
1. HTML: The initial HTML document is loaded for the main page, and subsequent interactions
might involve loading additional HTML pages for specific sections (e.g., video details).
2. JavaScript (JS): YouTube uses JavaScript for dynamic content updates, video playback, and
user interactions. In the case of a SPA, this may involve updating parts of the page without full
reloads.
3. CSS (Stylesheets): Stylesheets are downloaded to apply consistent styling to the content.
4. Images and Thumbnails: Images and video thumbnails are downloaded to enhance the visual
presentation.
5. Video Content: When watching a video, the actual video content is streamed or downloaded
progressively.
6. API Requests: YouTube makes various API requests to fetch data related to videos, user
interactions, and recommendations.
- Fonts: Both SPA and MPA approaches may download fonts for consistent text rendering.
- External Libraries: Dependencies and external libraries may be downloaded, such as jQuery or
other utility libraries.
- Tracking Pixels and Scripts: Both types may use analytics scripts and tracking pixels to collect
user data.
Benefits of SPA
We have learned about the differences between single-page applications (SPAs) and multi-page
applications (MPAs) in the last lesson. As a more modern approach, SPAs are much more
popular than MPA. If you check applications like Gmail, Facebook or, Twitter, they are using
SPAs. Also, many developers are following the SPA approach to develop web apps because of
their benefits.
To understand the benefits of SPA, first, need to understand the lifecycle of SPA (Figure 1).
When the user launches the SPA, the backend server loads the entire page (HTML/CSS page). It
will get all the application and presentation resources from the server.
As illustrated in Figure 1, as responses to user requests in AJAX, only the necessary data is
transferred in the form of JSON files to the client (user browser). That is, a SPA reloads only the
data required by the user.
Now, let’s see the benefits of SPA.
Benefits of SPA
1. Better Performance - Only a few items change when you click something or scroll
down the page, but the majority of the page remains unchanged. The backend
server does not send fully formed new HTML/CSS files for each user interaction. It
will only send a small amount of data. Since it loads only the data you asked for with
a click, it does not require additional page load time.
2. Improved User Experience - As the user does not need to wait for a new page to
load, it only changes content but not the page. Therefore, it gives the user a
seamless experience.
3. Use Less Bandwidth - SPAs use less bandwidth because they only load web pages
once.
4. Ease in Development of Apps - The SPA design separates front-end and backend
web development services. Therefore, front-end web development and backend
development can be considered as separate parts and both groups of developers
can work parallelly. Thus, web applications can be developed more quickly than
before. Also, a small front-end modification will not require the deployment of the
entire application.
5. Better Data Caching - SPA saves in the cache, all data received from the server in
response to the initial user request. It efficiently caches local data. Therefore, users
can even work offline. For example, we can consider offline mode in Gmail and
Google Docs. Later, the data on the user’s machine is synchronized with the data on
the backend server.
Even though there are many benefits of SPA, there are some disadvantages too.
Disadvantages of SPA
1. Problems with SEO - As SPAs do not usually have the typical structure of distinct
pages, each with its URL, search engines like Google or Bing may have difficulty
indexing the web content. Thus, there could be less visibility for single-page apps.
This can be avoided by employing strategies such as server-side rendering and
ensuring that clicks generate distinct URLs. Thus, no longer it is considered a major
problem. Also, search engines like Google have improved their indexing mechanisms
to support SPA.
2. Higher Downloading Time - Since all the resources are loaded on the initial page
view, some SPAs take a little longer to load on the first visit.
3. Uses of Browser Resources - Because the browser performs the majority of the
work for the SPAs, SPAs require a large number of resources from it. Creating SPAs
frequently requires that users use the most latest browsers that support some
modern functionalities.
4. Requires JavaScript - Single-page apps use JavaScript. The application will not work
unless users enable JavaScript in their web browser.
Activity 1
In this activity, we will be working with Google DOC (which is an example for SPAs).
To do this activity you need a Google account. If you do not have a Google account, you can
create a Google account.
Next, turn on "Offline Access" under Settings in Google Drive. Make sure that your document is
available offline.
Answer
Activity 2
Answer
Data caching is a technique used in computing to store frequently accessed or computed data
in a temporary storage area, typically faster to access than the original source. The purpose is
to improve the performance and efficiency of data retrieval operations by reducing the need to
fetch the data from the original source repeatedly.
1. Faster Data Access:- Caching allows data to be retrieved quickly from a local cache rather
than fetching it from the original source, reducing latency and improving response times.
2. Reduced Latency:- By keeping frequently accessed data closer to the application or user,
data caching minimizes the time it takes to retrieve information, reducing latency in data
access.
4. Bandwidth Savings:- Caching helps conserve bandwidth by minimizing the transfer of data
between the application and the data source. This is particularly beneficial in scenarios where
data is fetched over networks with limited bandwidth.
8. Cost Savings:- By reducing the load on servers and minimizing data transfer across networks,
caching contributes to cost savings in terms of server infrastructure and network bandwidth.
9. Improved User Experience:- Faster data access and reduced latency contribute to an
improved user experience. Applications respond more quickly, leading to increased user
satisfaction.
10. Resilience to Traffic Spikes:- Caching helps absorb sudden spikes in traffic by serving cached
data without putting excessive strain on backend systems. This contributes to better handling
of varying loads.
These frameworks will be used by you as a web developer. Thus, it is important that we
understand different SPA frameworks and how we can use them in our tasks.
What is a Framework?
A web development framework is a set of resources and tools for software developers to build
and manage web applications.
1. Reduce boilerplate code - Boilerplate codes are sections of code that are repeated in
multiple places with no variation.
2. Simplify the development environment.
3. Allows developers to dedicate their efforts to build the project requirements.
4. Accelerated development.
There are numerous SPA frameworks. We will go over them one by one.
Angular is a widely used SPA framework that is maintained by Google. It is TypeScript based.
Also, Angular is open source. Open-source software are the software whose original source
code is made freely available and may be redistributed and modified.
The first version of Angular as Angular 1.0 or AngularJS was released in 2010. Then, Angular
came as a major upgrade of AngularJS in 2016. Then, Angular came as a major upgrade of
AngularJS in 2016. Angular uses component-based architecture.
Figure 1 illustrates a user interface (UI) of marksheet with the student names and their marks.
The UI of a web app can be divided into components as in Figure 1. The main component is the
marksheet. As can be seen in Figure 1, components can have other components inside their
body (child components). Also, components can communicate with one another, and they can
be reused. For example, the search component (search box) in Figure 1 can be reused if you
want it in the student information UI, to filter students.
Angular is used by famous companies like Freelancer, PayPal, and Samsung (for their website).
React
React is a famous SPA development framework in the world, maintained by Facebook. It is also,
an open-source framework. Similar to Angular, React has a component-based architecture. It
follows the Virtual DOM (Document Object Model) concept. Simply, DOM is a tree structure
that can represent the content in a web page. You have learned about DOM in your previous
lessons. An HTML web page can be represented with a tree structure.
With a programming language, we can change the DOM structure dynamically. Via that, we can
make changes to the website. However, reading and writing to DOM is an expensive process.
Therefore, React introduces virtual DOM. A virtual DOM is a lightweight copy of actual DOM.
Thus, the Read/Write operations are not very expensive. React reads from this virtual DOM and
update it first. Then finally it updates the actual DOM. This leads to the improved performance
of React applications.
Activity 2
Select a simple website of your choice and draw the DOM structure.
Also, we can consider about [Link] as another popular SPA framework. Let’s learn about that
too.
[Link]
Vue has a component-based architecture, similar to Angular and React. Also, Vue has the
Virtual DOM concept like React. Vue is considered to have a small learning curve. As other
frameworks, this is also an open-source framework.
Table 2 gives a comparison between the frameworks we have learned in this lesson.
From the previous lessons we have been, discovering different SPA frameworks. From this
lesson onwards we will learn one of the widely used SPA development frameworks, named
Angular.
First, we will clarify the difference between Angular and AngularJS. Therefore, let’s investigate
how they evolve and their differences.
AngularJS
AngularJS is a Single Page Application development framework. It was initially released in 2010
and is maintained by Google and a community of individuals and corporations. AngularJS is
based on JavaScript, and it is open source. Open-source software is the software whose original
source code is made freely available and may be redistributed and modified.
Towards Angular
Since AngularJS was released in 2010 many developers used it and hence a large user base was
created. Anyway, the Angular team at google kept upgrading the framework. In 2016 they
released version 2.0 of AngularJS. This was a complete rewrite of the framework and hence was
a huge upgrade from previous releases. This new version has improved performance and is
faster than the initial version. Therefore, new users embraced this new version. This version 2.0
of AngularJS is now commonly named Angular.
Now you know how Angular evolved. Next, we will investigate the advantages of using Angular.
Why Angular?
As you already know angular is version 2 of AngularJS. If you follow this blog article (refer link 1
mentioned below), which is posted on Angular’s official blog site, you will understand that
AngularJS will not get any new features in the future. Officially Angular team at Google
promotes the developers to migrate to Angular from AngularJS. Therefore, if you are creating a
new project you should start with Angular.
Angular is based on Microsoft’s TypeScript. TypeScript is more advanced than JavaScript and
will help to avoid a lot of errors when building web apps. You will learn about TypeScript and its
advantages in the next lesson.
Angular has a better code structure. It is easy to create and manage large Angular applications
with this new structure. Angular has a tool called Angular CLI. With this, we can create and
serve web applications easily. So, this is also convenient for Angular developers. You will get to
use this tool in practicals in coming lessons.
Now you know the advantages of Angular over AngularJS. Next, do the following activity to
understand the core differences between Angular and AngularJS.
Activity 2
Create a table with two columns and compare and contrast the differences between Angular
and AngularJS.
Answer
Angular and AngularJS are both web application frameworks developed by Google, but they
have significant differences in terms of architecture, features, and syntax. Here's a comparison
of Angular and AngularJS:
1. Architecture:
- MVC Architecture: AngularJS follows the Model-View-Controller (MVC) architecture, but the
implementation is often closer to Model-View-ViewModel (MVVM).
2. Language:
- Digest Cycle: AngularJS uses a digest cycle to track changes and update the view. Two-way
data binding allows automatic synchronization between the model and view.
4. Directives:
- ng- Directives: AngularJS uses directives prefixed with "ng-" to extend HTML functionality.
Directives are a key aspect of creating dynamic and reusable components.
5. Dependency Injection:
- Implicit DI: AngularJS has implicit dependency injection, where dependencies are inferred
based on parameter names in functions.
6. Performance:
- Digest Cycle Overhead: The digest cycle can lead to performance issues, especially in large
applications, as it processes the entire scope hierarchy.
Angular (Angular 2 and above):
1. Architecture:
2. Language:
- One-Way Data Binding: Angular primarily uses one-way data binding (from component to
view), which is more predictable and easier to manage.
4. Directives:
5. Dependency Injection:
- Explicit DI: Angular uses explicit dependency injection. Dependencies are specified in the
constructor of a class, making it more modular and testable.
6. Performance:
- Change Detection: Angular's change detection mechanism is more efficient and allows for
better control over updates. This leads to improved performance, especially in large
applications.
7. Mobile Support:
8. Tooling:
- CLI Support: Angular comes with a powerful CLI (Command Line Interface) that simplifies
development tasks, such as scaffolding, testing, and deployment.
9. Ivy Renderer:
- Efficient Rendering: Angular introduces the Ivy renderer, which is more efficient in terms of
bundle size and runtime performance.
10. Modularity:
- NgModule System: Angular introduces the NgModule system for better modularity and
organization of code.
Commonalities:
2. Testing:- Both frameworks support testing and provide tools and utilities for writing unit tests
and end-to-end tests.
3. Official Support:- Both AngularJS and Angular are officially maintained by Google, providing
long-term support and updates.
Additional Reading
Introduction to TypeScript
As a web developer, to build web applications with Angular you must be familiar with
TypeScript. During this lesson we will get a basic understanding of what is TypeScript, its
features and advantages.
What is TypeScript?
TypeScript cannot run directly on web browsers. It builds on top of JavaScript. After writing a
TypeScript code, it can be compiled using a TypeScript compiler. In computing, compiling means
translating a computer code which is written in one language to another language. The
compiler generates a JavaScript file in the compilation, which can run directly on the browser.
This process is called “transpilation”. Figure 2 shows the process of TypeScript compilation.
The TypeScript source files are named with the .ts extension. A JavaScript file is generated with
the .js extension by the compiler.
Features of TypeScript
1. Strongly typed
TypeScript provides data types for variables, function parameters, and object properties. Hence
it is known as a strongly typed programming language.
Mentioning the data type of variable is not mandatory in TypeScript. It helps the compiler in
checking the types of variables and avoids errors when dealing with the data types.
In TypeScript, we can declare a variable using two keywords “var” and “let”. Following are some
examples for defining variables. In these examples “string” and “number” data types are used.
As can be seen above, a data type can be specified by using a colon after the variable name,
parameter, or object property.
Important:
Once an identifier is annotated with a type, it can only be used as that type. If the identifier is
used as a different type, the TypeScript compiler will issue an error.
In JavaScript, we use the var keyword to declare a variable. When it comes to TypeScript, there
is another keyword that you can use for declaring a variable. It is the “let” keyword. Now let’s
look at what are the differences between these two keywords.
There are mainly two keywords that you can use in TypeScript. Var and let keywords. The
scoping rules differ between them. First, let’s discuss the var keyword.
var
Declaring the variable in JavaScript has always been done using the var keyword. If you declare
a variable with the var keyword, it is defined throughout the program.
let
“let” is another keyword that can be used for declaring a variable in TypeScript. It is similar to
the var keyword, but it has some scoping restrictions compared to the var keyword. The
variables declared with the let keyword have block scope. That means the scope of let variables
is limited to their containing block. In TypeScript, you can only access that variable within that
block.
Data types of TypeScript can be categorized into two categories as shown in Figure 3.
o Primitive types
o User-defined types
Any
“any” is the supertype of all data types in TypeScript. In some cases, we may not have prior
knowledge about the data type of value that will be assigned to a variable. “any” data type can
be used in such cases.
Primitive Types
Number
“number” data type can be used to represent a double precision 64-bit floating-point values
which can be used to represent both integers and fractions.
String
Void
“void” is used on function return types to represent functions that do not return any value.
Null
“null” is used to represent an intentional absence of an object value. Only a null value can be
assigned to it.
Undefined
Never
“never” data type is used to represent the values that never occur.
E.g., The following function can never return a value because it always throws an exception. As
a result, the function's return type can be mentioned as never.
}
User-defined types
Array
Class
A class serves as a blueprint or template for creating objects. It provides state and behavior to
its objects. The data for the object is encapsulated in a class.
E.g.,
class person {
name: string;
address: string;
printMessage(): string {
return “hello”;
Interface
In other words, an interface specifies the syntax that any entity must be followed. Interfaces
define properties, methods, and events, which are the members of the interface. Interfaces
contain only the declaration of the members.
E.g.,
interface person {
name: string;
address: string;
printMessage(): string ; }
Tuple
This data type allows creating of an array where the type of a fixed number of elements is
known but does not have to be identical.
E.g.,
Enum
E.g.,
Function
E.g.,
function printName() {
[Link](“Malsha Gamage”);
2. Portable
TypeScript can run on different environments such as multiple browsers, devices, and operating
systems. Hence, we say TypeScript is portable.
TypeScript provides object-oriented features such as classes, interfaces, access modifiers, and
many more.
4. Supports all JavaScript libraries
TypeScript supports all JavaScript libraries such as jQuery, React because it is the superset of
JavaScript.
Now let’s have a look at the advantages of using TypeScript for creating web applications.
Advantages of TypeScript
Identify errors at compilation time - TypeScript codes are compiled before execution and
generate compilation errors if there are any syntax errors. This helps to highlight errors before
the code runs. But in JavaScript, errors are found at the run time and make it difficult to debug
the code.
Additional feature support - Features such as strong typing and object-oriented features makes
the code more powerful.
Activity 1
In this lesson, we have learned several data types that can be used in TypeScript. Read and
understand differences between those data types when using them in web applications.
Hint: You may go through the link given at the bottom of the lecture note.
Activity 2
TypeScript code segments are shown in following figures (Figure 4 and 5) and compile time
errors are underlined using red line. Check and identify the differences between "let" and "var"
keywords considering their scope.
Figure 4: A code example using the “var” keyword
Additional Reading
[Link]
Before installing Angular, you must have installed [Link] and npm package manager on your
computer. Let’s first learn what npm is.
What is npm?
Angular, Angular CLI and Angular applications rely on npm packages for many features. Npm
Package manager is required to download and install npm packages.
npm stands for Node package manager. npm is the world's largest software registry and it is
free to use. Furthermore, it is used by open-source developers to share and borrow packages.
You do not need to install npm package manager if you have already installed [Link]. It is
installed with [Link] by default.
[Link] Installation
Follow the below steps to install NodeJS in Windows. If you are using Linux and Mac OS
computer, the steps for installing [Link] are given in further reference.
1. Download the [Link] installer from the [Link] website (Link is given below in additional
readings). Click the “16.14.0 LTS Recommended for most users” button for download installer
for Windows (Figure 1). At the time this lecture note was written, version 16.14.0-x64 was the
latest version. (Download the latest recommended version.)
Important: The [Link] installer includes the npm package manager. So, do not need to install it
separately.
2. Once the installer finishes downloading, double click on it to launch the installer.
3. The system will ask if you want to run the software. Click Run.
5. In the next screen, review the license agreement will be displayed. Click the check box which
says, “I accept the terms in the License agreement” and click the Next button if you agree to the
terms and to install the software.
6. Then you must provide the installation location. Leave the default location unless you have a
specific need to install it in another location. If you need to specify a new location, click the
“change” button and select a new location.
7. Then custom setup screen will be displayed and leave the default if you do not need to
change. Click Next.
8. Then after the “Tools for native modules” the screen will be appeared. Click the check box on
the screen if you need to automatically install the necessary tools. Then click Next.
9. Finally, click the Install button to run the installer. Then it will start the installation process.
Wait until the installation completes. When it finishes, click Finish.
Verify installation
After you have installed [Link], you can check the version of [Link]. Run node –v command
in command line interface.
Then, run npm -v in the command line interface. It will show the npm package manager
version.
After successfully installing [Link], you may now install Angular CLI on your computer.
Angular installation
To verify the angular version, run the following command in command-line interface.
ng --version
Before installing Angular, you should have the following installed on your development
machine:
[Link]: Angular requires [Link], which includes npm (Node Package Manager). You can
download [Link] from the official website: [Link]
[Link] provides the runtime environment for JavaScript on the server side.
npm is used to manage packages and dependencies, including the Angular CLI.
Activity 1
Create a new Angular project using the Angular commands available on the Angular official
website. Hint:
[Link]
Activity 2
Read and understand more information about npm package manager. Hint:
[Link]
Additional Readings
[Link]
[Link]
Installation steps for Linux and Mac OS:
[Link]
[Link]
During previous lessons, we created our first Angular application. You might have also heard us
calling the application an Angular project. A project refers to the set of files that make up a
single independent Angular application. A collection of files that belong to one or more Angular
projects makes up the Angular workspace.
When we create an Angular project using the Angular CLI (Command-Line Interface), some files
and folders are created automatically inside the project workspace. These files and folders are
stored inside a single folder that has the same name as your new application. This folder is
called the ‘workspace root’.
Activity 1
As shown in the lesson video, create a new angular app called ‘my-first-app’ using the Angular
CLI. What is the name of your root folder or your workspace root?
The app has already been created at the bottom of the page for those of you who are using the
embedded code playground. You can use this playground to try out all the activities.
Activity 2
Look at the structure of your new Angular app that you have created just now. Identify three
files and three folders you can see inside the root folder.
Let’s move back to the lesson to understand those files and folders you have identified in
Activity 2.
These files inside the workspace root make up a simple skeleton application that is ready to be
run and edited.
Three main types of files and folders can be found inside the root folder.
These files define how the workspace is run and maintained so that the project can run
smoothly. You would only rarely need to edit these files manually. You can find the list of
workspace configuration files and what they are used for in Table 1 below.
File/Folder
Purpose
Name
This is a file related to something called ‘source control’. You will learn about this in a
.gitignore
later course.
Contains the configurations that apply to the Angular CLI by default in that
[Link]
workspace.
Contains all the npm package dependencies that are needed by all the projects in the
[Link]
workspace.
package- This is a more detailed version of the [Link] file. It contains extra information
[Link] like the version details of the npm packages used in the project.
node_modules
Contains all the npm packages that are needed by the whole workspace.
/
[Link] This file contains all the TypeScript configurations for the projects in the workspace.
The ‘e2e’ folder contains the configuration files and source files needed for testing your default
application. Any tests that you want to write should be written inside here.
Inside your workspace, you might have seen a folder called ‘src’. This is called the source folder
of the application and contains the source code of the default Angular project. This includes the
files for the root module (default Angular module) and root component (default Angular
component). You will learn more about modules and components in later lessons. The ‘app’
folder inside the ‘src’ folder contains these default files.
Application Source Files - These files support you to test and run your application. Table 2 and
Table 3 contain a list of these application source files and their uses.
File/Folder
Purpose
Name
Contains the files of the default component that holds the logic and data of the
app /
application. These are the files included:
assets / Contains images and other external resource files that we can use in our application.
This is the main HTML file that is loaded to the web browser when running the
[Link]
application.
When you try to run your application, this will be the first file that is compiled. It tells
[Link]
you where to find the root module of your application.
Contains a list of the style sheets that are applied to the project. The extension of this
[Link]
file can change depending on what type of styling you have configured for your project.
[Link] This is the starting point of the tests you write for your application.
The root module file defines how the components need to be loaded when
[Link]
rendering the application.
Table 3: Application source files that can be found inside the ‘app’ folder
Now let’s do another activity to see whether we have understood them well.
Activity 3
Go into your [Link] file and find where the dependencies are listed. Identify three
packages and their version information as shown in the file.
Activity 4
When you run your default application some content appears. Go to the HTML files in your
source folder, and find out whether the following content is coming from your [Link] file or
your [Link] files.
Further Reading