ui exam Flashcards

1
Q

Which of the following protocols is considered a connection oriented protocol?

A

Transmission Control
Protocol (TCP)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

In terms of a web application, what is meant by the term ‘scalability’?

A

its ability to handle a growing amount of user traffic, data, or workload without experiencing significant performance degradation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the ‘404’ status code in HTTP indicate?

A

the server cannot find the requested resource

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which protocol is used to transfer web pages from servers to browsers?

A

HyperText Transfer Protocol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which of the following does an HTTP cookie do?

A

track, personalize and save information about each user’s session.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the ‘S’ stand for in HTTPS

A

Secure

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

In an MVC (Model-View-Controller) architecture, what is the role of the ‘Controller’?

A

handles request flow, never handles data logic

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does DNS stand for in terms of the Internet and the World Wide Web?

A

Domain Name System

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How are IPv4 addresses expressed?

A

typically written in decimal digits, formatted as four 8-bit fields that are separated by periods 192.0.2.146

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

In AWS S3, what does S3 stand for?

A

Simple Storage Service,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which of the following are pricing model for AWS EC2 instances?

A

on demand, savings plan, spot instances

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How would you handle a sudden increase in traffic to your AWS hosted website?

A

Content Delivery Network (CDN)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Which service would you use to connect your on-premises data center to the AWS Cloud securely?

A

AWS Direct Connect

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Internet Protocol (IP)

A

is the fundamental protocol defining the Internet
* Subdivides information into packets
* Responsible for routing those packets over networks
* IP address is typically : 32-bit number (IPv4) or 128-bit (IPv6)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Hypertext Transfer Protocol (HTTP)—

A

a communications protocol used to send
information over the web
* HTTP is built on top of TCP

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

IP source software creates packets representing the data

A

Header : source and destination IP addresses, length of data, sequencing info, etc.
* Data itself – the payload

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

The World Wide Web

A

huge client-server system with millions of clients
and Web servers for accessing linked documents
* Comprises applications and protocols that run on top of the Internet
* Web Servers host thousands of hyperlinked documents or applications that dynamically
generate hyperlinked documents
* Browsers provide an easy-to-use interface for accessing and presenting those documents

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

GET

A

request to return a document to the client

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

HTTP POST

A

POST sends data to a specific URI and expects the resource at that
URI to handle the request

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Head

A

request to return the header of the document

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

HTTP PUT

A

PUT puts a file or resource at a specific Uniform Resource Identifier
(URI)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

delete

A

request to delete the document

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

URI

A

Uniform Resource Identifier

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Amazon RDS

A

(Relational Database Service): RDS offers managed database
services for popular database engines like MySQL, PostgreSQL, Oracle, and
Microsoft SQL Server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Amazon EC2
(Elastic Compute Cloud): EC2 provides virtual servers in the cloud, allowing users to easily scale their computing capacity up or down based on demand.
26
Amazon S3
(Simple Storage Service): S3 is a scalable object storage service that allows users to store and retrieve data, such as files, images, and videos, in the cloud.
27
Amazon DynamoDB:
DynamoDB is a fully managed NoSQL database service that provides low-latency and scalable storage for applications that require flexible and fast performance.
28
Some key services and features offered by AWS include:
Identity and Access Management (IAM): With AWS IAM, you can specify who or what can access services and resources in AWS, centrally managed fine-grained access control. * Virtual Private Cloud(VPC): Networking service with security group. * Lambda: Lambda is a serverless computing service that lets you run your code without provisioning or managing servers, based on event-driven architectures. * API Gateway – to create RESTful APIs * Route 53 – DNS service in AWS, allows to register domain names * CloudFormation – infrastructure as code – templatized configuration of collection of AWS resources * Amazon Sagemaker: a fully managed machine learning service that enables developers to build, train, and deploy machine learning models at scale.
29
Amazon VPC (Virtual Private Cloud)
Amazon VPC is virtual private network within the public AWS cloud that are logically isolated from the rest of the AWS Cloud * Resembles a traditional network in data centers * Enables you to launch AWS resources, such as EC2 instances into a virtual network. * A VPC is an AWS region specific, comprised of one or more subnets created in individual availability zones (AZs) * After you create a VPC, you can create subnets * A VPC is associated with a CIDR (Classless InterDomain Routing) range, which is essentially an IP address range, such as 10.0.0.0/16
30
Amazon Elastic Compute Cloud (EC2)
Amazon EC2 is used to create virtual machines called EC2 Instances in AWS * An EC2 instance provides a virtual computing environment with memory and process running together * You can use Amazon EC2 to launch virtual servers of different types, configure security and networking, and manage storage. * Amazon Machine Images (AMIs) – Preconfigured templates for EC2 instances that package the bits needed for the server (including the operating system and additional software) * Instance Types – Various configurations of CPU, memory, storage, and networking capacity for your instances
31
Features of Amazon EC2
Persistent Storage Volumes – Persistent storage volumes for your data using Amazon Elastic Block Store (Amazon EBS) * Security Group – An instance-level firewall that enables you to specify the protocols, ports, and source IP ranges that can reach your instances * Elastic IP addresses – Static IPv4 addresses for dynamic cloud computing, known as Elastic IP addresses * Metadata – Metadata, known as tags, that you can create and assign to your Amazon EC2 resources
32
rds key features
Key features and benefits of Amazon RDS include: * Managed Service: Amazon RDS handles administrative tasks such as hardware provisioning, database setup, software patching, backups, and automatic software upgrades. * This allows developers to focus on their applications rather than managing the underlying infrastructure. * Scalability: Amazon RDS enables you to scale your database resources up or down based on your application's needs. * You can easily adjust compute and storage capacity to handle changes in traffic, ensuring performance and availability. * High Availability: Amazon RDS provides built-in features for high availability, including automated backups, automated multi-AZ (availability zone) deployments, and automated failover. * These features help minimize downtime and ensure data durability.
33
Amazon S3 (Simple Storage Service)
Amazon S3 provides durable, highly-scalable object storage * Designed for 99.999999999% durability and 99.99% availability * Amazon S3 stores data as objects and objects are stored within folders that are called “buckets”
34
Which HTML element is used to include external JavaScript files?
78
Bootstrap Containers
Container has a concept of containing elements to wrap the site content. * Containers are used to contain, pad, and align your content within a given device or viewport. * It ensures that the content remains centered and properly aligned regardless of the screen size. * It also adds responsive left and right margins to the content that adjusts based on the device used to render the content. * This means that on smaller devices left and right margins will be smaller too. three different container classes: .container - the .container class creates a responsive fixed-width container that adjusts its size based on the screen width. * .container-{breakpoint}, which refers to 100% width until the specified breakpoint * .container-fluid - the .container-fluid class provides a full width container, spanning the entire width of the viewport * The viewport is the area of a web page that's visible to the user. The viewport is fundamental to web development, since its dimensions are what control how page elements appear. The viewport is a rectangle, the size of which is determined by the size of the user's device, such as mobile devices.
79
Bootstrap Grid system
The CSS Bootstrap Grid system provides a 2D structure comprising intersecting straight lines (vertical & horizontal) to structure the contents. * It allows you to create a flexible grid of rows and columns for organizing and aligning content on a web page. * It provides support for creating responsive designs that automatically adjust and adapt to different screen sizes and devices. * The Bootstrap grid system is based on a 12-column layout, where you can divide the available horizontal space into 12 equal-width columns. * You can then allocate a specific number of columns to each element within a row to control their width and arrangement. using grid system: Containers: The grid system starts with a container, which acts as a wrapper for the content. * Bootstrap requires a containing element to wrap site contents and house our grid system. * We use .container class for proper alignment and padding. Without a container, the grid won't work properly. * Rows inside the container: you create rows using the .row class, which acts as horizontal containers for columns and ensure proper alignment and spacing. * We use .row to create horizontal groups of columns. Content should place inside the columns. * Columns within each row: you can divide the available space into columns using the .col-* classes, where * represents a number between 1 and 12. * For example, .col-6 creates a column that occupies half of the row's width, while .col-3 creates a column that occupies one-fourth of the row's width. * You can use any combination so that the sum be equal to 12. Only columns should be the immediate children of rows. * Responsive Behavior: Bootstrap's grid system is responsive by default.
80
Bootstrap images and Responsive Images
consist of three main classes * img-rounded * img-circle * img-thumbnail Images in Bootstrap are made responsive with .img-fluid. * Responsive images automatically adjust to fit the size of the screen. * Create responsive images by adding an .img-fluid class to the tag. The image will then scale nicely to the parent element.
81
bootstrap Buttons
Bootstrap 5 provides different styles for buttons * Bootstrap has a base .btn class that sets up basic styles such as padding and content alignment. * By default, .btn controls have a transparent border and background color and lack any explicit focus and hover styles. * Bootstrap includes several button variants, each serving its own semantic purpose.
82
Navigation Menu
If you want to create a simple horizontal menu, add the .nav class to a
    element, followed by .nav-item for each
  • and add the .nav-link class to their links:
83
Navbar
A navigation bar is a navigation header that is placed at the top of the page A standard navigation bar is created with the .navbar class, followed by a responsive collapsing class: .navbar-expand-xxl|xl|lg|md|sm * stacks the navbar vertically on xxlarge, extra-large, large, medium or small screens * To add links inside the navbar, use either an
84
Bootstrap Tabs
Bootstrap turns the nav menu into navigation tabs with the .nav-tabs class. * Takes the basic nav from above and adds the .nav-tabs class to generate a tabbed interface. * Add the .active class to the active/current link. * Clicking another tab will toggle the visibility of this one for the next. * The tab JavaScript swaps classes to control the content visibility and styling.
85
Bootstrap Tables
There are four main classes for tables * .table * .table-striped * .table-bordered * .table-hover * The class .table based tables uses the most basic table style with just some light padding and horizontal dividers. .table-striped class adds zebra-stripes to a table – striped rows * .table-bordered is used to get borders surrounding every element and rounded corners around the entire table * .table-hover is used to get a light grey background to rows while the mouse cursor come over it. * .table-responsive – by wrapping any in table-responsive class we can make responsive table
86
Forms in Bootstrap 5
Bootstrap 5 provides a comprehensive set of styles and classes for creating responsive forms that adapt to different screen sizes and devices. * Bootstrap forms allow you to structure and style various input elements, such as text fields, checkboxes, radio buttons, dropdowns, etc. in a consistent and visually appealing manner. * You can apply built-in CSS classes to your HTML elements to achieve the desired styling and functionality. Bootstrap 5 form classes include: * .form-control: Applies styles to text fields, text areas, and other input elements. * .form-check: To group and styles checkboxes with their labels. .form-check class ensures proper margins for labels and checkbox. In addition, .form-check: is also used to group radio buttons and their labels. .form-check class ensures proper margins for labels and radio buttons. * .form-check-input : For styling checkboxes and radio buttons. * .form-check-label: For styling checkbox labels and radio buttons labels. * .form-select: Styles dropdown/select elements. * .form-range: Styles range/slider input elements. * .form-floating: Creates floating labels for input elements.
87
In Bootstrap, what class is used to create a basic table style?
base class .table
88
Which class provides a responsive, fixed width container in Bootstrap?
.container
89
Why use Bootstrap?
Pre-made HTML & CSS templates. * Faster development with premade classes, stylings, responsive-grid, etc. * Easy to learn if we have basic knowledge on HTML and CSS. * Mobile first approach. * Responsive layouts - Bootstrap's responsive CSS adjusts to phones, tablets, and desktops - resize, hide, shrink, enlarge or move content to make it look good. * Platform independent web pages - compatible with almost all modern browsers.
90
Using Grid system
Containers: The grid system starts with a container, which acts as a wrapper for the content. * Rows inside the container: you create rows using the .row class. Rows act as horizontal containers for columns and ensure proper alignment and spacing. * Columns within each row: you can divide the available space into columns using the .col-* classes, where * represents a number between 1 and 12. * For example, .col-6 creates a column that occupies half of the row's width, while .col-3 creates a column that occupies one-fourth of the row's width. * You can use any combination so that the sum be equal to 12 * Responsive Behavior: Bootstrap's grid system is responsive by default. * Example: Responsive Bootstrap’s grid system with 3 columns
91
Key features of JavaScript
Client-Side Scripting: JavaScript code is primarily executed on the client-side, meaning it runs on the user's web browser rather than the web server. * However, it can also be used on the server-side through technologies like Node.js. * Dynamic Content: JavaScript enables the modification of web page content in real-time, allowing developers to create interactive elements that respond to user input. * JavaScript interacts with the Document Object Model (DOM) of a web page, allowing developers to modify the structure, content, and styles of HTML elements dynamically. * Event Handling: JavaScript functions can be used as event handlers that allow developers to respond to various user actions, such as clicks, mouse movements, keyboard inputs, and form submissions. * Cross-Browser Compatibility: JavaScript is supported by all major web browsers, making it a versatile language for web development.
92
Variables in JavaScript
Keyword var is used to declare the names of variables A variable name can be any valid identifier consisting of letters, digits, underscores ( _ ) and dollar signs ($) that does not begin with a digit and is not a reserved JavaScript keyword. * Declarations end with a semicolon (;) * Can be split over several lines, with each variable in the declaration separated by a comma * When a variable is declared in JavaScript, but is not given a default value, it has an undefined value. * Attempting to use the value of such a variable is normally a logic error. * Comments * A single-line comment begins with the characters // and terminates at the end of the line * Multiline comments begin with delimiter /* and end with delimiter */ * Comments are ignored by the JavaScript interpreter
93
Keywords
abstract arguments await* boolean break byte case catch char class* const* continue debugger default delete do double else enum* eval export* extends* false final finally float for function goto if implements import* in instanceof int interface let* long native new null package private protected public return short static super* switch synchronized this throw throws transient true try typeof var void volatile while with yield
94
What is the result of '2' + 2 in JavaScript?
22
95
What does the 'break' statement do in a JavaScript loop?
gets out of the loop
96
How would you select an element with the ID 'myElement' in JavaScript?
let element = document. getElementById("myElement");
97
Control Structures in JavaScript
Specify the order in which statements are to be executed in a computer program * Most programs can be written in terms of three control structures * sequence * selection * repetition * Sequential execution - execute statements in the order they appear in the code * Selection and repetition include transfer of control * Changing the order in which statements execute
98
JavaScript Function
n JavaScript, a function is a block of code that is designed to perform a specific task or calculate a value. * It is a reusable piece of code that can be invoked (called) multiple times from different parts of a program function functionName(param1){ var name = param1 return name } function: The function keyword is used to declare a function. * functionName: This is the name given to the function, which can be used to invoke the function later. The name should follow the rules for variable names in JavaScript. * parameters: Functions can accept zero or more parameters (also known as arguments), which are placeholders for values that are passed into the function when it is called. * code: The code block enclosed within curly braces {} represents the body of the function. It contains the statements and expressions that define the functionality of the function. * return: The return statement is used to specify the value that the function should return when it is called. * Variables declared in function definitions are local variables * they can be accessed only in the function in which they are defined * A function’s parameters are considered to be local variables
99
Program Modules
JavaScript programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects available in Web browsers * JavaScript provides several built-in objects that have a rich collection of methods for performing * Common mathematical calculations * String manipulations * Date and time manipulations * Manipulations of collections of data called arrays * The term method implies that a function belongs to a particular object * All others are referred to as functions. * JavaScript is sometimes referred to as an object-based programming language
100
document
document object methods and properties * For manipulating the document that is currently visible in the browser window - getElementById(id) returns the DOM node representing the XHTML element whose id attribute matches id - write(string) writes the string to the xhtml document as xhtml code and adds a newline character at the end -cookie a string containing the values of all cookies stored on the user's computer for the current document -lastModified: the date and time that this document was last modified - writeln() method writes a String to the html document and adds a new line character at the end.
101
window object
methods for manipulating browser windows -open() Opens a new browser window -prompt() Displays a dialog box that prompts the visitor for input -close() Closes the current window -focus() Sets focus to the current window -blur() Removes focus from the current window -document Returns the Document object for the window. See also The Document Object. --closed Returns a boolean true if a window is closed -opener Returns a reference to the window that created the window
102
Global object
- escape: takes a string argument and returns a string in which any character not in asciiformat is encoded in hexadecimal -eval() Evaluates a string and executes it as if it was script code -isFinite() Determines whether a value is a finite, legal number -isNaN() Determines whether a value is an illegal number parseFloat() Parses a string and returns a floating point number -parseInt() Parses a string and returns an integer -unescape: decodes a string that was previously encoded
103
Math object methods
abs(x) Returns the absolute value of x ceil(x) Returns x, rounded upwards to the nearest integer ceil(x) Returns x, rounded upwards to the nearest integer exp(x) Returns the value of Ex floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithmof x max(x1,x2,..) Returns the number with the highest value min(x1,x2,..) Returns the number with the lowest value pow(x, y) Returns the value of x to the power of y round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle the rest have Math. first: E Returns Euler's number (approx. 2.718) LN2 Returns the natural logarithm of 2 (approx. 0.693) LN10 Returns the natural logarithm of 10 (approx. 2.302) LOG2E Returns the base-2 logarithm of E (approx. 1.442) LOG10E Returns the base-10 logarithm of E (approx. 0.434) PI Returns PI (approx. 3.14) SQRT1_2 Returns the square root of 1/2 (approx. 0.707) SQRT2 Returns the square root of 2 (approx. 1.414)
104
String Object
charAt() Returns the character at a specified index (position) charCodeAt() Returns the Unicode of the character at a specified index concat() Returns two or more joined strings indexOf() Returns the index (position) of the first occurrence of a value in a string lastIndexOf() Returns the index (position) of the last occurrence of a value in a string fromCharCode() Returns Unicode values as characters replace() Searches a string for a pattern, and returns a string where the first match is replaced slice() Extracts a part of a string and returns a new string split() Splits a string into an array of substrings substr() Extracts a number of characters from a string, from a start index (position) substring() Extracts characters from a string, between two specified indices (positions) toLowerCase() Returns a string converted to lowercase letters toUpperCase() Returns a string converted to uppercase letters anchor() Displays a string as an anchor fixed() Displays a string using a fixed-pitch font link() Displays a string as a hyperlink strike() Displays a string with a strikethrough sub() Displays a string as subscript text sup() Displays a string as superscript text
105
Date Object
Date object provides methods for date and time manipulations * You can create new Date objects using Date constructors * The Date constructor with no arguments initializes the Date object with the local computer’s current date and time * Can create a new Date object by supplying arguments to the Date constructor for year, month, date, hours, minutes, seconds and milliseconds. * Hours, minutes, seconds and milliseconds arguments are all optional * Includes a rich set of methods for date and time manipulations
106
Cookies
Cookies are small pieces of data that are stored on a user’s computer. * Used to store user’s information or to track their browsing behavior. * Your web browser stores it locally to remember the “name-value pair” that identifies you. * When a user returns to that site in the future, the web browser returns that data to the web server in the form of a cookie.
107
Setting a cookie
To set a cookie, you can use the document.cookie property. * Syntax to set cookie: “identifier=value” where * identifier is any valid JavaScript variable identifier, and * value is the value of the cookie variable * When multiple cookies exist for one website, identifier-value pairs are separated by semicolons (;) in the document.cookie string * expires property in a cookie string sets an expiration date, after which the web browser deletes the cookie * If a cookie’s expiration date is not set, then the cookie expires by default after the user closes the browser window * Here's an example that sets a cookie named "username" with the value "John Doe" and an expiration date of one year from the current date: * document.cookie = "username=John Doe; expires=" + new Date(new Date().getFullYear() + 1, new Date().getMonth(), new Date().getDate()).toUTCString(); * Assignment operator does not overwrite the entire list of cookies, but appends a cookie to the end of it
108
Getting a cookie
To retrieve the value of a cookie, you can read the document.cookie property. * The document.cookie property returns a string that contains all the cookies set on the current domain, so you need to parse it to get the specific cookie you're interested in.
109
Deleting a cookie
To delete a cookie, you can set its expiration date to a past date. This will cause the browser to remove the cookie. * Here's an example that deletes the "username" cookie:
110
event-driven programming
A user interacts with a GUI component that creates events * A script is notified of the event * The script processes the event * The function that is called when an event occurs is known as an event-handling function or event handler. * Events and event handling help make web applications more responsive, dynamic and interactive * For example: * An HTML element’s onclick attribute indicates the action to take when the user of the HTML document clicks on the element * Event Handler * JavaScript functions that is called to handle events * Registering an event handler * Refers to assigning an event handler to an event on a DOM node
111
Registering Event Handlers
Inline model * Treats events as attributes of HTML elements * Assigns the name of the function to an HTML event attribute * Value of the event attribute is a JavaScript statement/function to be executed when the event occurs * Traditional model * Assigns the name of the function to the event property of a DOM node * The value of the event property of a DOM node is the name of a function to be called when the event occurs
112
Common Events
onabort script Script to be run on abort onchange script Fires the moment when the value of the element is changed onclick script Fires on a mouse click on the element ondblclick script Fires on a mouse double-click on the element onkeydown script Fires when a user is pressing a key onkeypress script Fires when a user presses a key onkeyup script Fires when a user releases a key onmousedown script Fires when a mouse button is pressed down on an element onmousemove script Fires when the mouse pointer is moving while it is over an element onmouseout script Fires when the mouse pointer moves out of an element onmouseover script Fires when the mouse pointer moves over an element onmouseup script Fires when a mouse button is released over an element onload script Fires after the page is finished loading onunload script Fires once a page has unloaded (or the browser window has been closed) onsubmit script Fires when a form is submitted
113
JSON Data Types
String: A sequence of characters enclosed in double quotes. * Number: An integer or floating-point number. * Boolean: Either true or false. * Null: Represents the absence of a value. * Array: An ordered list of values, enclosed in square brackets []. * Object: A collection of key-value pairs, enclosed in curly braces {}.
114
Accessing JSON Data:
In JavaScript, you can access JSON data using dot notation or square bracket notation. (same way at work)
115
Modifying JSON Data:
You can modify JSON data by assigning new values to the desired key.
116
Converting JSON to a String:
To transmit or store JSON data, you need to convert it to a string using JSON.stringify()
117
Converting a String to JSON:
To work with JSON data received as a string, you can convert it to a JavaScript object using JSON.parse()
118
JavaScript eval function
Can convert JSON strings into JavaScript objects * To evaluate a JSON string properly, a left parenthesis should be placed at the beginning of the string and a right parenthesis at the end of the string before the string is passed to the eval function * A secure way to process JSON is to use a JSON parser
119
JSON and AJAX
JSON is often used in combination with AJAX to retrieve data from a server asynchronously. * You can make an AJAX request to a server and receive the response in JSON format.
120
AJAX – Asynchronous JavaScript and XML
AJAX is a technique used to send and retrieve data from a server asynchronously without reloading the entire web page. It enables building dynamic and interactive web applications. * It enables asynchronous communication between a web browser and a server, allowing data to be retrieved, sent, and processed in the background, without disrupting the user experience. * It allows you to update parts of a web page without requiring a full page reload. * While the name implies XML, modern AJAX implementations often use JSON as the preferred data format due to its simplicity and efficiency. * Modern JavaScript frameworks, such as jQuery, Axios, and Fetch API, provide higher-level abstractions and helper functions to simplify the process of making AJAX requests and handling server responses.
121
Here's how AJAX typically works:
XMLHttpRequest: The XMLHttpRequest object is a built-in browser object that allows you to send and receive data asynchronously from a server. It allows JavaScript to make HTTP requests to a server and handle the server's responses asynchronously. * Asynchronous Requests: With AJAX, you can send asynchronous requests to the server without blocking the execution of other JavaScript code or requiring a page reload. This means that users can continue interacting with the page while data is being fetched or processed in the background. * Event-driven Programming: AJAX relies on event-driven programming, where you define callbacks or event handlers that are triggered when certain events occur, such as the completion of an AJAX request or the receipt of a server response. * Updating the DOM: Once the server responds with data, you can use JavaScript to dynamically update the web page's content (e.g., displaying the retrieved data) without refreshing the entire page
122
XMLHttpRequest state properties and methods
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4: 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready responseText Returns the response data as a string responseXML Returns the response data as XML data status Returns the status-number (e.g. "404" for "Not Found" or "200" for "OK") statusText Returns the status-text (e.g. "Not Found" or "OK") abort() Cancels the current request getAllResponseHeaders() Returns header information getResponseHeader() Returns specific header information open(method,url,async,uname,pswd) Specifies the type of request, the URL, if the request should be handled asynchronously or not, and other optional attributes of a request method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous) send(string) send(string) Sends the request off to the server. string: Only used for POST requests setRequestHeader() Adds a label/value pair to the header to be sent
123
Creating Ajax Applications using the XMLHttpRequest object
Set Up the Development Environment: * Create a new HTML file or use an existing one. * Include the necessary JavaScript code in your HTML file. * Create an XMLHttpRequest Object: * Create an instance of the XMLHttpRequest object using the new XMLHttpRequest() constructor. * Make an Asynchronous Request: * Use the XMLHttpRequest object to make an asynchronous HTTP request to the server. * Use the open() method to specify the HTTP method (GET, POST, etc.) and the URL of the server-side script or API endpoint. * Use the send() method to send the request to the server. For POST requests, include the request payload as an argument to the send() method. * Handle the Server Response: * Register an event handler function to handle the response from the server. * Use the onreadystatechange event and check the readyState property of the XMLHttpRequest object to determine the current state of the request. * Inside the event handler function, check if the readyState is 4 (indicating that the request is complete) and the status is 200 (indicating a successful response). * Access the response data using the responseText property of the XMLHttpRequest object
124
Creating Ajax Applications using the XMLHttpRequest object pt2
Display the Response: * Update the HTML content of your web page to display the retrieved data. * Use JavaScript to access and modify the HTML elements. * For example, you can use the innerHTML property to update the content of a specific element. * Handle Errors: * Implement error handling to handle failed AJAX requests or server errors. * Check the status property of the XMLHttpRequest object to determine the status code of the response. * Display appropriate error messages or handle errors gracefully. * Send Data to the Server: * AJAX requests can also send data to the server. * For POST requests, include the request payload in the send() method as a string, typically in the format of URL-encoded parameters or JSON data. * Enhance User Experience: * Use AJAX to perform dynamic updates without page reloads. * Implement features like auto-complete, live search, or real-time data updates. * Update specific parts of the web page selectively, without reloading the entire page. Cross-Origin Resource Sharing (CORS): * Understand CORS if you're making AJAX requests to a different domain or port. * Ensure that the server supports and allows cross-origin requests. * Set appropriate CORS headers on the server-side to enable access from different origins. * Testing and Debugging: * Use browser developer tools to inspect AJAX requests and responses. * Debug and troubleshoot any issues that may arise. * Validate and verify the data exchanged between the client and server.
125
how to use AJAX
var async; try{ async = new XMLHttpRequest(); async.onreadystatechange = stateChange (this is a different function); async.open('GET', url,true async.send(null) }
126
Key features of TypeScript
Static Typing: TypeScript introduces static typing, allowing you to specify types for variables, function parameters, and return values. * This helps catch errors during development and provides better tooling support, such as code completion and refactoring. – Type Inference: TypeScript can infer the types of variables and expressions based on their usage. This means that you don't always have to explicitly annotate types, as TypeScript can often determine them automatically. – Object-oriented Programming: TypeScript supports object-oriented programming concepts like classes, interfaces, inheritance, and access modifiers. – ECMAScript Compatibility: TypeScript is designed to align with the evolving ECMAScript (JavaScript) standards. – Advanced Tooling: TypeScript comes with a rich set of developer tools, including a compiler that translates TypeScript code to JavaScript, code editors with intelligent autocompletion and code navigation.
127
TypeScript
TypeScript is a superset of JavaScript. – It supports all JavaScript syntax and adds additional features for type checking and static types.TypeScript is written in .ts file – Create a new TypeScript file with a .ts extension, e.g., app.ts – TypeScript files contain TypeScript code that will be compiled to JavaScript. – You can compile a TypeScript file (app.ts) using TypeScript compiler tsc, using %tsc app.ts – This command will compile the TypeScript file into JavaScript and generate an app.js file.
128
TypeScript Grammar
let and const are two new types of variable declarations in JavaScript. * let is similar to var in some respects * const is an augmentation of let in that it prevents re-assignment to a variable
129
functions params
TypeScript functions allow optional and default parameters optional: var?:type default: var = 'doe'
130
TypeScript Types
string – number – boolean – Date – Array – any * Custom types
131
TypeScript Interfaces
TypeScript interfaces provide a code contract
132
TypeScript Interface and Class
In TypeScript, the two types (i.e., Interface and Class) are compatible if their internal structure is compatible. – This allows us to implement an interface just by having the shape the interface requires, without an explicit implements clause.
133
What is angular?
Angular uses the concept of Single Page Application (SPA) * A fully contained application in the browser * that do not need to make requests for new pages on the server. * Usually makes request just of the data that will be rendered inside of the pages * Accesses backend via REST+JSON services * SPA Advantage: Faster application, * Eliminates the download of HTML, JS, and CSS code in each request * Service Oriented Front-End Architecture (SOFEA) – can be considered as a synonym of Single Page Application
134
Key Features of Angular
TypeScript: Angular is built with TypeScript, a superset of JavaScript that adds static typing and other features to enhance developer productivity and maintainability. * Component-Based Architecture: Angular follows a component-based architecture where the application is divided into reusable and self-contained units called components. Each component represents a specific part of the user interface and encapsulates its own data, logic, and template. * Templates and Directives: Angular utilizes HTML templates to define the structure and layout of the user interface. It extends HTML with additional syntax and directives, such as *ngFor and *ngIf, to enable dynamic rendering, data binding, and other advanced features. * Data Binding: Angular provides a powerful data binding mechanism that allows for synchronization between the component's data and the template. It supports both one-way and two-way data binding, making it easier to keep the UI in sync with the underlying data. * Dependency Injection: Angular has a built-in dependency injection system that helps manage the creation and sharing of instances of objects (services) within the application. This promotes modularity, reusability, and testability of the code. * Routing: Angular's router allows developers to implement navigation between different views or components within the application. It supports features like lazy loading, route parameters, and nested routes. * Reactive Extensions (RxJS): Angular leverages RxJS, a library for reactive programming, to handle asynchronous operations, such as HTTP requests, event handling, and data streams.
135
Angular Components
A component consists of three things: * A component class that handles data and functionality. * An HTML template that determines the UI. * Component-specific styles that define the look and feel.
136
Property Binding
Property binding is one way of binding data in Angular. * The square braces are used to bind data to a property of an element * The trick is to put the property onto the element wrapped in brackets: [property]. for example: [label] = "'test taking'"
137
Angular Interpolation
Angular interpolation is used to display a component (class) property in the respective view (html) template with double curly braces {{ }} syntax * Interpolation is used for one way data binding. * Interpolation moves data in one direction from our components class to HTML elements. The property name to be displayed in the view template is enclosed in double curly braces {{ }} also known as moustache syntax. * Angular automatically pulls the value of the propertyName and object.propertyName from the component and inserts those values into the browser. * Angular updates the display when these properties change. example: {{data.Max}}
138
Angular Interpolation Usages
Display simple properties – To display and evaluate strings into the text between HTML element tags and within attribute assignments. * Evaluate arithmetic expressions – To evaluate arithmetic expressions present within the curly braces. * Invoke methods and display return values – To invoke methods on hosting component views within interpolation expressions. * Display array items – We can use interpolation along with ngFor directive to display an array of items.
139
Event Binding
(click) for button
140
Two-way Data Binding
This essentially means that if there is data in the component (model), bind it to the view; and if the data changes in view then bind it back to the component. * With two-way data binding, the angular framework not only watches your variables in the model (.ts file) for changes, it also keeps track of changes made by the user (for example with input-elements) and updates the variables accordingly. – That way, the variables in the component code always represent what is displayed in the view. * A commonly used directive that makes two-way data binding possible is called ngModel. ngModel can be used with form-elements like inputs to implement two-way data binding. * To do that, we use a special syntax: [(ngModel)] – It's a combination of the one-way- and the event binding syntax. – Generally referred to as a “Banana In A Box” syntax * It is used as follows in the .html file:
141
Looping with *ngFor directive
*ngFor is a "structural directive" to shape or reshape the DOM's structure, typically by – adding, removing, and manipulating the elements to which they are attached. * Any directive with an asterisk, *, is a structural directive. * We use *ngFor by adding it as an attribute of the html element that you want to repeat, such as

element. * *ngFor=“” takes an expression that consist of two parts: – the array to loop over and – the element item that will contain the value during the iteration. * The syntax of the expression is “let item of items” where – items is the array you will loop over and – the item is the current element in that iteration.

142
Using *ngIf directive
*ngIf correspond to if block in programming languages. * It evaluates a condition and if the condition is true only then the template bound to that ngIf is displayed. – In fact, ngIf removes the element from the DOM if the corresponding expression evaluates to false. * For example, if product.description is empty, then the inner

should not be rendered

143
Styles for Angular Components
* Styles of a component for all html tags/elements used in xxxxcomponent.html file can be specified inside xxxx.component.css file. * Styles specified in xxxx.component.css file applies only to the component it belongs to.
144
Creating and using multiple modules
To create a module and be able to use its component outside this module, we need to do the following: – Module that needs this new module needs to import it – Whatever module the component is declared in has to export the component * That is, what needs to be imported is the module itself, e.g., AppModule imports ViewModule. * And, what is being exported is the component, that is the module that contains the component, i.e., ViewModule needs to export the component This allows the component declared in a module to be usable in another module. * This will allow the app-component.html which is part of AppModule to be able use tag, which is part of ViewModule.
145
Creating a Service
In Angular, a service is a class that is responsible for providing specific functionality and data to different parts of an application. * Angular service classes contain methods with specific functionality that can be reused across multiple different components. To create a service in Angular, you typically use the Angular CLI to generate a new service file. * The service class is then decorated with the @Injectable() decorator, which allows the service to be injected as a dependency into components or other services. * Once the service is registered with Angular's dependency injection system, it can be injected into any component that needs its functionality. * To create a service called ‘test’ – Open Visual Studio Code (by typing code . (period) in the work workspace) and open a new Terminal in the Visual Studio Code and then – Use Angular CLI command Services that you declare in your module needs to be listed in the providers: section of @NgModule, – which is an annotation for AppModule class in src/app/app.module.ts * declarations section contain all the components that are part of the module, – providers: contain all services that are part of the module, – imports: contain all other modules that this module depends on. * In order to add the test service in the AppModule, add TestService class into the providers: array
146
Dependency Injection
Dependency Injection (DI) is a design pattern and a core concept in Angular that enables the efficient management and sharing of dependencies between different parts of an application. It is a way to provide instances of objects (dependencies) to the classes or components that require them, rather than having the classes create the dependencies themselves.
147
angular Making REST calls with HttpClient
To use that service, we need to import the module that the service comes with. – The module contains service in the providers: section. (In this case, it’s internal angular module.) – When you import that module in any one of your modules, that service gets added to the injection context, the global service context so that it’s available for all your components to use. * Typically, HttpClient module is imported in the root module, that is AppModule inside app-module.ts * The name of the module is HttpClientModule, as imported in the AppModule next. As observable calls a function (e.g., console.log() when job is done, this function can ask the observable to pass the API response to it when done fetching the API response. – Done by passing an argument to the function (line 18, 19)
148
Angular Routing
Routing in Web applications generally refers to navigating between pages. * Routing in an angular application though refers to navigating from one angular component’s view to another – As users interact with the web application to perform application tasks, they need to move between the different views that you have defined. – In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. * Angular provides RouterModule that enables navigating from one view to another by switching between components – The Router enables navigation by interpreting a browser URL as an instruction to change the view
149
Angular Routing Enablers
Route – Route tells the Angular Router which view to display when a user clicks a link or pastes a URL into the browser address bar. – Every Route consists of a path and a component it is mapped to. The Router object parses and builds the final URL using the Route * Routes – Routes is an array of Route objects our application supports; defines a set of paths that determine which component’s view to display when a user clicks a hyperlink – An array for mapping URL paths to components * Router – APIs provided by RouterModule to perform navigation – An Angular Router is a service (Angular Router API) that enables navigation from one component to the next component as users perform application tasks like clicking on links and buttons on the browser. RouterLink – Tells angular router which view to load – The RouterLink is a directive that binds the HTML element to a Route. – Clicking on the HTML element, which is bound to a RouterLink, will result in navigation to the Route. * RouterOutlet – Specifies where the router render a particular view – The RouterOutlet is a directive () that serves as a placeholder, where the Router should display the view
150
Four steps to define navigation in Angular applications
Define a const variable of type Routes with an array of objects mapping url paths to components – Register the const variable with RouterModule.forRoot() with @NgModule of the module ts class – Create a hyperlink using a tag with the attribute routerLink pointing to the path defines in the Routes array – Use specify to indicate where to the router should render the view pointed by the path.
151
Angular Forms
Forms are used to gather user input – Applications use forms to enable users to log in, to register, and to perform many other data-entry tasks. * When user submits the form, Angular’s http service sends data to server – Angular can validate the data before sending it to server * Angular provides two different approaches to handling user input through forms: – Template-driven Form – Reactive Form
152
Template-driven Form
– With a template driven form, the structure of the form is defined in the angular component’s template (html file) using predefined directives provided by Angular – Most logic of the form goes into the html file – Easy to use, ideal for simple forms – Makes use of ngModel directives
153
Reactive Form
Most logic goes into the component class (.ts file) and then you assign it to the form – Gives more flexibility to build complex forms – Uses a separate set of directives
154
Fundamental Building Blocks of Angular Forms
FormControl – Every single html form input elements, such as input type text, radio button, dropdown, etc. are called FormControls – Each input element is a FormControl; it’s the smaller unit – Tracks the values and validation of individual form elements * FormGroup – A collection of form elements makes a FormGroup * FormArray – This has similar kind of collection of FormControls in an array format * ControlValueAccessor – Creates a bridge between Angular FormControl instances and native DOM elements
155
Key Steps to use in Template Driven Forms
FormModule – Enable Template Driven Forms by adding FormsModule to our application root module. * ngForm – Get a reference to the ngForm directive, which is implicitly applied to all HTML
elements by the Angular Forms module. – This directive is responsible for tracking the overall value of the form , which contains the values of all of its form fields. – The ngForm directive will also keep track of the overall validity state of the form, which is dependent on the validity state of its form fields. ngModel – Apply ngModel directive to each form control. This directive will bind to the corresponding HTML element with the ngForm. – The ngModel directive keeps track of the value typed in by the user with each key pressed, and it will also keep track of the validity state of that particular form control only. – The ngForm parent directive will then interact with all its child ngModel directives, and build a model of the whole form, with all its field values and validity states. * ngSubmit – Use ngSubmit directive for event binding so that when a use clicks submit button, the event handler method in the component class gets called. – The ngSubmit directive allows us to access the native form submission event and add it a click handler instead.
156