web development - ajax and fetch

0.0(0)
studied byStudied by 7 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/56

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

57 Terms

1
New cards

client
server

What are the key components of a client-server web architecture?

  • ____ side: Handles rendering and user interactions (e.g., browser).

  • ____ Side: Manages storage and computations (e.g., web server).

  • Network Communications: Facilitates data exchange between the client and server over the network.

2
New cards

1-way
2-way

sync

async

Communication Dimensions

Given the general pattern is the communication we a number dimensions to consider

  • ______ - fire and forget, just send something to the server and move on

  • ____ - send a request, receive a response

  • _______ - send a request and block the code/UI until a response is received

  • ______ - send a request and move on waking up later upon response

We should recall that JavaScript support asynchronous coding and given the nature of network requests we are likely going that way, but know synchronous does make sense. While 2-way communication is most likely a 1-way style might make sense for monitoring, ‘heart beating’, or analytics

3
New cards

cookies

query string

local storage

session storage

indexDB

HTTP headers

state management

the pure HTML is stateless, we need place to store state data

Method

Description

Use Cases

Advantages

Disadvantages

_________

Small pieces of data stored in the browser, sent with every HTTP request.

Authentication, user preferences, session tracking.

- Persistent across sessions.
- Can be set as HttpOnly to prevent XSS attacks.

- Limited storage (4KB per domain).
- Sent with every request, increasing bandwidth.
- Can be stolen via XSS if not secured properly.

____ ______

Data appended to a URL in ?key=value format.

Filtering, pagination, tracking, sharing links.

- Easy to use and bookmarkable.
- No storage required.

- Visible in URLs (security risk).
- Limited length (~2000 characters).
- Cannot store sensitive information.

______

______

Key-value storage in the browser that persists indefinitely.

Storing preferences, caching API responses, offline storage.

- Larger storage (5MB per domain).
- Persistent even after closing the browser.
- Fast access.

- Accessible via JavaScript (security risk).
- Cannot be sent with HTTP requests.
- No automatic expiration.

______

________

Similar to localStorage, but data is cleared when the browser tab closes.

Temporary data storage, multi-step forms, session-based data.

- Isolated per tab, avoiding data conflicts.
- Fast access.

- Not persistent beyond session.
- Limited storage (5MB).

______

A NoSQL database stored in the browser for structured data.

Complex offline storage, caching large datasets.

- Stores large amounts of data.
- Indexed for efficient searching.

- More complex API than localStorage.
- Requires async access (Promises).

_____

______

Headers sent with requests and responses, used for authentication, caching, security.

Authentication (Authorization header), security (CORS, X-Frame-Options), caching.

- Secure when using HttpOnly cookies or headers.
- Not directly accessible via JavaScript.

- Requires server-side support.
- Cannot store complex data easily.

4
New cards

setItem

getItem

setItem

removeItem

localstorage.clear()

JSON.stringify

JSON.parse

5mb

HttpOnly cookies

localstorage

  • key value based, CRUD:

    • create: __________

    • read: _______

    • update: _____

    • delete: _______

  • remove all localstorage pairs: __________

  • since can only store strings, when try to retrive/store JSON objects:

    • localStorage.setItem("user", _________(obj));

    • const user = _________(localStorage.getItem("user"))

  • storage capacity is limited to ________ per domain

Security Concerns:

  • Client-Side Nature: Since localStorage is stored in the browser, it can be accessed and tampered with via developer tools.

  • No Encryption: All stored data is plain text, meaning sensitive information like passwords should never be stored here.

  • XSS Vulnerabilities: If your site is vulnerable to Cross-Site Scripting (XSS) attacks, malicious scripts can exploit localStorage.

  • Tampering Risk: End-users with access to their browser's developer tools can manipulate localStorage values.

Best Practices:

  • Use localStorage for non-sensitive, application-specific data (e.g., theme settings, UI preferences).

  • Employ input validation and sanitize any data used in conjunction with localStorage to prevent injection attacks.

  • For sensitive data, consider __________ ______ or secure server-side storage.

  • Avoid excessive reliance on localStorage for performance-critical applications due to its synchronous nature (blocking).

5
New cards

x-www-form-urlencoded

the encoded query string has a content type of ____________

6
New cards

https://example.com
“GET”

i want to submit the form data to example.com using GET, fill in the atttributes:

<form action=_____ method=_______>

7
New cards

_blank

i want to open the link in a new window:

<a href=".." target=______>a link</a>

8
New cards

_self

i want to open the link in the current page:

<a href=".." target=______>a link</a>

9
New cards

asynchrous javascript and XML

AJax stands for __________ ________ __________ _______

10
New cards

event
without

AJAX comunication

  • Client Side:

    • Represents a user interacting with a web page.

    • User activities trigger ___ such as clicking buttons, entering data, or navigating content.

  • AJAX Communication Layer:

    • Handles asynchronous requests ____(with/without) requiring a full page reload.

    • Captures user events and sends requests to the server.

    • Updates the UI dynamically when new data is received.

  • Server Side:

    • Processes requests from the client asynchronously.

    • Sends back the required data for the requested updates.

  • Time Flow:

    • The process occurs in a sequence over time.

    • The client sends a request, the server processes it, and data is transmitted back.

<p>AJAX comunication</p><ul><li><p><strong>Client Side</strong>:</p><ul><li><p>Represents a user interacting with a web page.</p></li><li><p>User activities trigger ___ such as clicking buttons, entering data, or navigating content.</p></li></ul></li><li><p><strong>AJAX Communication Layer</strong>:</p><ul><li><p>Handles asynchronous requests ____(with/without) requiring a full page reload.</p></li><li><p>Captures user events and sends requests to the server.</p></li><li><p>Updates the UI dynamically when new data is received.</p></li></ul></li><li><p><strong>Server Side</strong>:</p><ul><li><p>Processes requests from the client asynchronously.</p></li><li><p>Sends back the required data for the requested updates.</p></li></ul></li><li><p><strong>Time Flow</strong>:</p><ul><li><p>The process occurs in a sequence over time.</p></li><li><p>The client sends a request, the server processes it, and data is transmitted back.</p></li></ul></li></ul><p></p>
11
New cards

model view controller

mvc standstard for:
m________ v___________ c_______

12
New cards

same origin policy

_____ ___________ __________ restricts scripts from accessing resources from different origins, allowing access only within the same origin.

13
New cards

cross-origin Resource sharing

What is the HTTP header mechanism that helps handle SOP restrictions?

________ ________ ___________ _______

14
New cards

FALSE

Is disabling access control on the browser or server safe?

15
New cards

least priviledged access

What is the principle that suggests careful privilege allocation in systems?
_________ __________ _______

16
New cards

same

At the HTTP level, requests made by <iframe>, XHR, fetch, sendBeacon, and other communication methods look ______________ (same/different).

17
New cards

true

If we emit a presentational neutral format for our endpoint, we can decouple our front end and back end.

18
New cards

HTTP headers

response codes

network conditions

MIME types

When making Ajax/Fetch requests, we must be aware of HTTP ______________, ______________ codes, ______________ conditions, and ______________ types.

19
New cards

MIME

____ type refers to Multipurpose Internet Mail Extensions, used to identify the media type across internet

20
New cards

JSON

The most common format for request transmission in modern web applications is ______________.

21
New cards

onreadystatechange()

promise

A main difference between XHR and Fetch is that XHR uses ______________(), while Fetch uses ______________.

22
New cards

less

Fetch tends to have ______________ (more/less) code compared to XHR in simple cases.

23
New cards

Fetch

The API introduced to allow progressive network enhancement is called ______________.

24
New cards

Progressive Enhancement

The design philosophy that emphasizes progressively improving network communication is called ______________.

25
New cards

Progressive Web Application

A web application that utilizes progressive network communication is called a ______________.

26
New cards

Ajax/Fetch

regulatory bodies

Browser restrictions on mobile devices have partially limited the adoption of ______________ technology due to ______________.

27
New cards

fetch

then

catch

____('https://api.example.com/data')
  ._____(response => {
    if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data))
  .____(error => console.error('Fetch error:', error));

28
New cards

open

onreadystatechange

readyState

status

send

window

abort

const xhr = new XMLHttpRequest();
xhr.___('GET', 'https://api.example.com/data', true);
xhr.______ = function () {
  if (xhr._______=== 4 && xhr._____=== 200) {
    console.log(JSON.parse(xhr.responseText));
  }
};
xhr.______();

// set timeout for 3 seconds  
timeoutID = _____.setTimeout( function() {cancelRequest(xhr);}, 3000); 

function cancelRequest(xhr){ 
 xhr._____(); 
 alert("Sorry, your request timed out."); 
}

29
New cards

method

URL

async (boolean)

xhr.open(_____, ____, _____ [,username,password])

30
New cards

uninitialized

open

sent

receiving

loaded

ready state property of XHR request

0: ________

1: ________

2: ________

3: ________

4: ____________

31
New cards

text/xml

the response type of XHR request is responseXML, with MIME type ________

32
New cards

incremental

Ajax allows for _______ updates, breaking the traditional post-wait-full page paint approach.

33
New cards

redundent

server

network

JavaScript

Ajax Advantages:

  • Ajax reduces __________ transmission by sending only necessary data.

  • One benefit of Ajax is the creation of more sophisticated and responsive user interfaces.

  • Ajax minimizes __________ load by reducing long-term requests.

Ajax Drawbacks:

  1. The increased number of queries in Ajax may lead to higher __________ utilization.

  2. Ajax applications can face issues like bookmarking, back buttons, and searchability challenges

  3. Poorly designed Ajax can negatively impact browser performance due to excessive _________.

34
New cards

HttpOnly

__________ Cookies are recommended to mitigate XSS attacks.

35
New cards

Cross-Site Scripting

XSS attackes refers to ___________

How XSS Attacks Work:

  1. Injection of Malicious Code: An attacker finds an entry point in a web application, such as a search bar, comment section, or even URL parameter, to input their malicious script.

  2. Script Execution: The vulnerable website fails to properly sanitize the input, and the malicious script is returned as part of the webpage content.

  3. User Impact: When a user interacts with the affected page, their browser executes the malicious script, thinking it’s legitimate.

Preventing XSS Attacks:

  • Input Validation: Sanitize and validate all user inputs to prevent malicious code from being processed.

  • Encoding Output: Ensure data is properly encoded when displayed, especially in HTML, JavaScript, or URL contexts.

  • Content Security Policy (CSP): Implement CSP headers to restrict the execution of untrusted scripts.

  • HttpOnly Cookies: Use HttpOnly flags for cookies to make them inaccessible to JavaScript and prevent theft.

36
New cards

data

Ajax makes it essential to sanitize __________ to avoid security vulnerabilities.

37
New cards

responseText

text()

XMLHttpRequest’s __________ property holds an unparsed string of the response.

the equivalent in fetch is the __________ promise

38
New cards

header

The PHP function __________ is used to set headers for no-cache in server-side responses.

39
New cards

XMLHttpRequest

onreadystatechange

XMLHttpRequest.DONE/4

parse

open

setRequestHeader

send

function onLoadRemote() {
    const req = new _________();
    req.___________= function() {
        if (req.readyState == ________) {
            const articles = JSON.______(req.responseText);
            if (articles.message) {
                alert(articles.message);
                return;
            }
            renderArticles(articles);
        }
    }
    req._____('GET', 'https://api.jsonbin.io/v3/b/..../latest', true);
    req._________('X-Master-Key', "....");
    req.setRequestHeader('X-Bin-Meta', 'false');
    req.____();
}

finish this function that gets json from remote jsonbin.io

40
New cards

blob

URL.createObjectURL

fetch(`/api/dashboard/rec/image`, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
    	"prompt": prompt,
        "width": 800,
        "height": 400,
    }),
}).then(response => {
    return response.___();
}).then(blob => {
    outputImage.setAttribute("src", ________(blob));
}).catch(error => {
    console.error("unable to fetch image: " + error.message, error);
    outputImage.setAttribute("alt", "unable to fetch image");
    outputImage.setAttribute("src", "https://picsum.photos/800/400");})

fill code that returns a jpg

41
New cards

eval/JSON.parse


let responseObject = ______(xhr.responseText);

how to evaluate JSON respose:

42
New cards

UTF-8

use ___________ for charsets and ajax

43
New cards

x-www-form-urlencoded

We need to be aware of the standard _________ it is required and often the preferred sole method for requests given the hassle of encode/decode

44
New cards

Basic Problems

  • •A request never returns

  • •A request returns but too slowly

  • •A request returns and is in error

Error Possibilities

  • The Web server throws an error

  • •The server-side framework throws an error

  • •The application throws an error

  • •The application returns erroneous data (format, type, etc.)

•Add in multiple requests particularly when there are dependencies and even more fun ensue

45
New cards

timeout

retry

the request is sent but does not return., we will wait for a period of time and then error out (_____) or try again (______)

46
New cards
const xhr = new XMLHttpRequest();
xhr.open('GET', '/endpoint', true);
xhr.timeout = 3000;
xhr.send(null);

i want to use XMLHttpRequest to do following:

call a GET async request to the /endpoint, set timeout to 3s, send null.

47
New cards

ok

client

server

HTTP error code

200: _____

4xx: _________ error

5xx: ________ error

48
New cards

stateless

Networking Secret Weapon

  • •Networking is your secret weapon as a web dev

  • •Know HTTP = Understanding + Security + Performance

•Security

  • •Three things in, three things out + ________

  • •Law: Trust no data, trust no user

  • •Technique: Validate your inputs, sanitize your outputs, look for anomalous behaviors

•Performance

  • •Law: Send less data, less often from nearby

  • •Techniques: Compression, omission, combination, caching, content distribution network

49
New cards

proxy

____________:

calls a script on the server of delivery (within the same origin) that calls remote web service on your behalf and pass the result back

  • avoid same origin issue

  • puts burden on server to forward requests

  • can be exploited

50
New cards

URL forwarding

_____________:

  • a variation of the previous method

  • calls a URL on the server with the same origin, which acts as a proxy redirect that pipes data transparently to a remote resource and back

  • use mod_rewrite

limitations:

  • burden on server to forward requests

51
New cards

script

__________ tag around:

makes call to remote service using <script> tag that returns a wrapped JSON response invoking a function in the hosting page

  • not restricted by same origin

  • scripts transport not as flexible as XHR

  • script responses and JSON responses shown to have some security concerns ….

52
New cards

binary bridge

______________:

  • use flash and java applet to make a connection to another domain

53
New cards

screen

___________ scrapping:

scraping = extracting contents from unwilling or unknowing sites with DOM, Xpath and the like

defense:

  1. CAPTCHA defense

  2. banning

  3. assume markup stability

54
New cards

mashup

_______:

Combine some Web services together and make something new

55
New cards

Push

___________:

A communications pattern initially called “comet” aims for a push model keeping a connection open between the browser and server so that the server can stream or push messages to the browser at will

<p>___________: </p><p>A communications pattern initially called “comet” aims for a push model keeping a connection open between the browser and server so that the server can stream or push messages to the browser at will</p>
56
New cards

socket

ws://

wss://

____________:

•We can do real time bi-directional ’stateful’ communication between a browser and server over the Web

  • •Starts first with an HTTP standard URL and switches to a socket with _______ or ________ style URL

•For standard simple request style apps (ex. CRUD apps) the idea is overkill, for games, chat, collaborative apps, real time data, etc. it is superior to any of the previous ideas even if occasional block/compat issues are encountere

57
New cards