Week 8 - client side interaction with services Flashcards

1
Q

Flashcard 1:
Front:
What is the Document Object Model (DOM), and how is it structured?

A

Definition: The DOM is a tree-like representation of any structured document (e.g., HTML or XML), allowing dynamic interaction and manipulation.

Structure:
Root node: Represents the document (e.g., <html> for HTML or the root element in XML).
Child nodes: Tags like <head>, <body> (HTML) or <book>, <title> (XML).
Further branches: Sub-elements or attributes.
Leaf nodes: Content like "Hello world!" or "Good morning!".
Purpose: The DOM provides a programming interface to access, modify, or interact with document elements, whether for web development or data processing.</title></book>

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

Javascript can access the dom dynamically to change content , structure and style of a web page

A

NOTE

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

what the dom would look like for this?

<!DOCTYPE html>

<html>
<head>
<title>Example Page</title>
</head>
<body>
<p>Hello, World!</p>
<ul>
<li>First Item</li>
<li>Second Item</li>
</ul>
</body>
</html>

A

Document
|
<html>
┌────────────┴────────────┐
<head> <body>
| |

<title> <p> Hello, World!
| |
"Example Page" <ul>
┌──────┴──────┐
<li> <li>
| |
"First Item" "Second Item"
</li></li></ul></p></title>

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

good vid for dom events

A

https://youtu.be/0fy9TCcX8Uc?si=_Uj72-SvFD4PPlVc

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

Front:
What is a script in HTML, and why is it used?

A

Definition: A script is a piece of JavaScript code added to an HTML document to make the webpage interactive or dynamic.

Uses:
Showing alerts (e.g., alert(‘Hello!’)).
Validating form inputs before submission.
Handling user actions like clicks or keypresses.
Animating webpage elements.

How it’s added:
Inline: Inside an element.
Internal: Inside a

 tag in the same HTML file.
External: In a separate .js file, linked to the HTML file.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Front:
What are inline scripts in HTML? Give an example.

A

Definition: JavaScript code added directly into an HTML element using attributes like onclick, onload, etc.

Example:
<button>Click Me</button>

How It Works:
The onclick attribute triggers the alert(‘Hello!’) when the button is clicked.

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

What are the advantages and disadvantages of inline scripts?

A

Pros:

Quick to implement: Ideal for small, simple actions like showing an alert when a button is clicked.
No separate file needed: Everything is contained in one place (HTML file).
Cons:

Not reusable: Each element requires its own script.
Example of redundancy:

<button>Button 1</button>
<button>Button 2</button>

Updating the alert requires changes in multiple places.
Hard to maintain: Mixing JavaScript into HTML clutters the code.
Less secure: Inline scripts are prone to XSS (Cross-Site Scripting) attacks.
Bad separation of concerns: HTML (structure) and JavaScript (behavior) are not clearly separated.

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

What are internal scripts in HTML? Give an example.

A

JavaScript code written inside a

 tag within the same HTML file.

Example:

<!DOCTYPE html>

<html>
<head>

<script>
function greet() {
        alert('Hello!');
      }
</script>

</head>
<body>
<button>Click Me</button>
</body>
</html>

How It Works:
The

 tag defines a function (greet()), which is triggered by the onclick attribute when the button is clicked.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the advantages and disadvantages of internal scripts?

A

Pros:
Centralized code: All JavaScript is in one place, making it easier to manage.
Reusable within the document: Functions like greet() can be used for multiple elements.
Example of reuse:
html
Copy code
<button>Button 1</button>
<button>Button 2</button>

Cons:
Limited reusability: The script is tied to this specific document. To use the same script on another HTML file, you must copy and paste it.

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

JavaScript code written in a separate .js file and included in the HTML file using a

 tag.

Example:
HTML File:

<!DOCTYPE html>

<html>
<head>



</head>
<body>
<button>Click Me</button>
</body>
</html>

script.js File:
function greet() {
alert(‘Hello!’);
}

How It Works:
The

 tag in the HTML file links to the external script.js file.
The greet() function is defined in script.js and can be used in any HTML file that includes this script.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the advantages and disadvantages of external scripts?

A

Pros:

Reusability: The same script can be used across multiple pages.
Example:

<!-- index.html -->


<!-- about.html -->


Any changes to script.js automatically apply to all pages.
Better maintainability: JavaScript is kept separate from HTML, making both easier to read and debug.
Performance: External scripts can be cached by browsers, improving page load speed for returning users.
Separation of concerns: HTML (structure) and JavaScript (behavior) are clearly separated.
Cons:

Requires an extra file: You need to manage an additional .js file.
Initial load time: If the external file is large or slow to load, it can delay page rendering.

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

What values are allowed in JSON key-value pairs?

A

We are discussing values in the key-value pairs of JSON.
Keys in JSON must always be strings (e.g., “key”: “value”).

Allowed Values in JSON
JSON key-value pairs allow the following data types as values:

Strings: “example”
Numbers: 42
Booleans: true, false
Arrays: [“apple”, “banana”]
Objects: { “key”: “value” }
Null: null

Key Takeaway:

JSON is strict and designed for data exchange. Only basic, language-independent types are allowed.
Keys in JSON must always be strings.

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

What values are allowed in JavaScript object key-value pairs?

note javascript can obviously also have the basic types like JSON as well we are talking about further examples of values

A

JavaScript objects allow all JSON-supported types and more:

Functions:
javascript
Copy code
let obj = {
greet: function() { return “Hello!”; }
};
Dates:
javascript
Copy code
let obj = {
createdAt: new Date()
};
Undefined:
javascript
Copy code
let obj = {
value: undefined
};
Key Takeaway:

JavaScript objects are more flexible, allowing dynamic types like functions, dates, and undefined.
Keys in JavaScript objects can be strings, numbers, or valid identifiers (e.g., title: “Introduction”).

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

Front:
What is the purpose of JSON.parse() in JavaScript?

A

Purpose: Converts a JSON string (received from the server) into a JavaScript object so it can be manipulated in code.

When to use:
When receiving data from a server.

Example:

let jsonData = ‘{“name”: “Alice”, “age”: 25}’; // JSON string
let jsObject = JSON.parse(jsonData); // Converts to a JavaScript object

console.log(jsObject.name); // Outputs: Alice
console.log(jsObject.age); // Outputs: 25

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

What is the purpose of JSON.stringify() in JavaScript?

A

Purpose: Converts a JavaScript object into a JSON string to send it to the server.
When to use: When sending or returning data to a server.
Example:

let jsObject = { name: “Alice”, age: 25 }; // JavaScript object
let jsonData = JSON.stringify(jsObject); // Converts to JSON string
console.log(jsonData); // Outputs: {“name”:”Alice”,”age”:25}

Key Note:
In this example, we see that when the JavaScript object becomes a JSON string, JSON enforces that all keys must be strings (e.g., “name” instead of name).

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

What happens to special values like functions, dates, and undefined when using JSON.stringify()?

A

stringify = Javascript -> JSON

Functions: Omitted in the JSON string.
Undefined: Omitted in the JSON string.
Dates: Automatically converted into an ISO string format.
Examples:

// Functions and undefined are omitted
let obj1 = { value: undefined, greet: function() { return “Hi!”; } };
console.log(JSON.stringify(obj1)); // Outputs: {}

// Dates are converted to strings
let obj2 = { date: new Date() };
console.log(JSON.stringify(obj2)); // Outputs: {“date”:”2024-01-01T12:00:00.000Z”}

17
Q

What is the key difference between JSON.parse() and JSON.stringify()?

A

JSON.parse():
Converts a JSON string into a JavaScript object.
Used for receiving data from a server.

JSON.stringify():
Converts a JavaScript object into a JSON string.
Used for sending data to a server.

18
Q

What is AJAX, and why is it important?

A

AJAX:
Stands for Asynchronous JavaScript and XML.

Purpose:
Allows web pages to send and receive data from the server without reloading the entire page.

Key Benefit:
Only the specific data needed is sent back, reducing server load and making the page feel faster and more interactive.

19
Q

How does AJAX work?

A

Asynchronous communication: Browser sends/receives data in the background.
No page reloads: Updates only the part of the page that needs it.
Only the specific data needed is sent back, making interactions faster and lighter.
Uses JavaScript to handle requests and responses.
Communicates with the server via XMLHttpRequest (XHR).

20
Q

What’s the difference between using AJAX and not using AJAX?

A

Without AJAX:

Every request to the server reloads the entire page.

Example: Submitting a form refreshes the entire page and resets unsaved data.

With AJAX:

Only the specific data needed is sent back, reducing unnecessary page reloads.

Example: Clicking “like” on a post updates the like count instantly without refreshing the page.

21
Q

What formats can AJAX requests and responses use?

A

JSON (most common).
Text files.
HTML.
XML.

22
Q

Front:
How does the conventional model of a web application work?

A

1)User interacts with the user interface.
2)Browser sends an HTTP request to the server.
3)Server processes the request, interacts with databases, and sends back an entire HTML page (with CSS).
4)Browser reloads and renders the whole page again.

Drawbacks:

Inefficient: Reloads the entire page even for small updates.
Slower user experience: Visible page reloads disrupt continuity.
Higher server load: Redundant data (like layout and styles) sent repeatedly.
Blocking Behavior: While the request is running, the entire user interface becomes unresponsive.

23
Q

How does the AJAX model of a web application work?

A

1)User interacts with the user interface.
2)Browser sends an asynchronous HTTP request via JavaScript (AJAX engine).
3) Server processes the request and sends back only the specific data needed (e.g., JSON, XML, or partial HTML).
4) The AJAX engine updates just the relevant part of the page without a full reload.

Efficient: Only the required data is exchanged.
Faster user experience: No visible reloads; updates are dynamic.
Reduced server load: Minimal data is sent, avoiding redundant transfers.
Non-Blocking Behavior:
The user interface remains interactive while the background request runs.
Example: You can scroll through a page or interact with other elements while a new portion of the page is loading in the background.

24
Q

What is the role of the AJAX engine in the AJAX model?

A

Acts as a middle layer between the browser and the server.

Key Responsibility:

The user interface no longer sends HTTP requests directly; instead, the AJAX engine does.
This allows the user interface to remain responsive while background requests run.
Responsibilities of the AJAX Engine:

Sends asynchronous HTTP requests to the server.
Processes the server’s response (e.g., JSON, XML).
Dynamically updates specific parts of the page without requiring a full reload.

25
Q

How does AJAX work?

A

An event occurs: A user interacts with the webpage (e.g., clicks a button).

AJAX engine creates a request: JavaScript creates an XMLHttpRequest object.

Request sent to server: The XMLHttpRequest object sends an HTTP request to the server.

Server processes the request: The server interacts with databases or other systems to generate the required response.

Server sends a response: Only the specific data needed (e.g., JSON, XML, or HTML) is sent back to the browser.

JavaScript reads the response: The response is processed by the AJAX engine.

Page updates dynamically: JavaScript performs actions (like updating part of the webpage) without reloading the page, ensuring the user interface remains interactive.

26
Q

retrieve data

A

let xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://example.com/data’, true);
xhr.send(); // No body for GET
xhr.onload = function () {
if (xhr.status === 200) {
console.log(‘Response:’, xhr.responseText); // Success
} else {
console.log(‘Error:’, xhr.status);
}
};

27
Q

send data

A

let xhr = new XMLHttpRequest();
xhr.open(‘POST’, ‘https://example.com/upload’, true);
xhr.setRequestHeader(‘Content-Type’, ‘application/json’); // Specify data type
let data = JSON.stringify({ username: ‘JaneDoe’, password: ‘password123’ });
xhr.send(data); // Body with data
xhr.onload = function () {
if (xhr.status === 200) {
console.log(‘Response:’, xhr.responseText); // Success
} else {
console.log(‘Error:’, xhr.status);
}
};