Skip to content

Latest commit

 

History

History
568 lines (387 loc) · 8.07 KB

File metadata and controls

568 lines (387 loc) · 8.07 KB


Asynchronous JS, AJAX and APIs

![[Media/Pasted image 20260612191224.png]]

![[Media/Pasted image 20260612191233.png]]

![[Media/Pasted image 20260612191238.png]]

![[Media/Pasted image 20260612191245.png]]

![[Media/Pasted image 20260612191252.png]]


HOW THE WEB WORKS: REQUESTS AND RESPONSES

![[Media/Pasted image 20260612191322.png]]

![[Media/Pasted image 20260612191328.png]]


Introduction to Asynchronous JS, AJAX and APIs

Asynchronous JavaScript allows JavaScript to start a long-running task and continue running other code while waiting for that task to finish.

Common async tasks:

timers
loading images
getting user location
fetching data from an API
reading files

Synchronous JavaScript

Synchronous code runs line by line.

console.log('Start');

console.log('Middle');

console.log('End');

Output:

Start
Middle
End

Each line waits for the previous line to finish.


Problem with Synchronous Code

If one line takes a long time, everything after it must wait.

console.log('Start');

// imagine this takes 5 seconds
console.log('Loading big data...');

console.log('End');

This can block the page.

[!warning] Warning
JavaScript runs on a single main thread, so long synchronous tasks can freeze the UI.


Asynchronous JavaScript

Asynchronous code starts a task now, but handles the result later.

console.log('Start');

setTimeout(() => {
  console.log('Timer finished');
}, 3000);

console.log('End');

Output:

Start
End
Timer finished

setTimeout() does not block the rest of the code.

[!tip] Mental Model
Async JavaScript says:
“Start this task, continue the code, and come back when it is done.”


Synchronous vs Asynchronous

Type Meaning
Synchronous Code waits line by line
Asynchronous Code can continue while waiting
Blocking Stops other code from running
Non-blocking Allows other code to continue

Example: Image Loading

Loading an image is asynchronous.

const img = document.createElement('img');

img.src = 'image.jpg';

img.addEventListener('load', function () {
  console.log('Image loaded');
});

console.log('Image is loading...');

Output:

Image is loading...
Image loaded

The browser loads the image in the background.


What Is AJAX?

AJAX stands for:

Asynchronous JavaScript And XML

It allows JavaScript to communicate with a web server without reloading the page.

[!important] Important
Even though AJAX has XML in the name, modern APIs usually send data as JSON.


What AJAX Does

AJAX allows a website to:

request data from a server
receive data from a server
update the page dynamically
avoid full page reloads

Example use cases:

weather app
country information app
Google Maps
search suggestions
login forms
infinite scrolling

Traditional Website vs AJAX Website

Traditional Website

User clicks button
↓
Browser reloads whole page
↓
New HTML comes from server

AJAX Website

User clicks button
↓
JavaScript requests data
↓
Server sends data
↓
Page updates without reload

[!success] Benefit
AJAX makes websites feel faster and more dynamic.


What Is an API?

API stands for:

Application Programming Interface

Simple meaning:

A way for one piece of software to talk to another piece of software.

In web development, an API usually lets your JavaScript app get data from another server.


API Example

A country API might return data like this:

{
  "name": "India",
  "capital": "New Delhi",
  "population": 1400000000,
  "region": "Asia"
}

Your JavaScript can request this data and display it on the page.


What Is a Web API?

A Web API is an API available over the internet.

Example:

https://some-api.com/countries/india

Your browser sends a request.

The server sends back data.


Request and Response

AJAX works using a request-response cycle.

Client/browser → request → server
Client/browser ← response ← server

Example:

Browser asks: Give me data about Portugal
Server replies: Here is Portugal data as JSON

What Is JSON?

JSON stands for:

JavaScript Object Notation

It looks like a JavaScript object, but it is actually a text format.

{
  "country": "Portugal",
  "capital": "Lisbon",
  "population": 10300000
}

[!important] Important
JSON keys must use double quotes.

Correct JSON:

{
  "name": "Jonas"
}

Invalid JSON:

{
  name: "Jonas"
}

JSON vs JavaScript Object

JavaScript object:

const user = {
  name: 'Jonas',
  age: 30,
};

JSON:

{
  "name": "Jonas",
  "age": 30
}
JavaScript Object JSON
Used inside JS code Used for data exchange
Keys may be unquoted Keys must be double-quoted
Can contain methods Cannot contain methods

How JavaScript Gets API Data

Modern JavaScript usually uses:

fetch()

Basic example:


fetch('https://example.com/ap')
  .then(response => response.json())
  .then(data => console.log(data));

This means:

1. Send request
2. Wait for response
3. Convert response to JSON
4. Use the data

Older AJAX: XMLHttpRequest

Before fetch(), developers used XMLHttpRequest.

const request = new XMLHttpRequest();

request.open('GET', 'https://example.com/api');
request.send();

request.addEventListener('load', function () {
  console.log(this.responseText);
});

[!info] Note
XMLHttpRequest still works, but fetch() is more modern and cleaner.


Async Does Not Mean Faster

Asynchronous does not mean the task finishes faster.

It means JavaScript does not wait and block everything.

setTimeout(() => {
  console.log('Done');
}, 3000);

console.log('Waiting...');

Output:

Waiting...
Done

The timer still takes 3 seconds, but the rest of the code continues.


Callback Functions in Async Code

A callback is a function that runs later.

setTimeout(() => {
  console.log('Runs later');
}, 2000);

The function inside setTimeout() is a callback.

It runs after 2 seconds.

[!tip] Remember
Async code often uses callbacks, promises, or async/await.


Common Async Tools

Tool Use
setTimeout() Run code once later
setInterval() Run code repeatedly
fetch() Request data from APIs
Promises Handle future values
async/await Cleaner promise syntax

Common Beginner Confusion

Why Does This Print in This Order?

console.log('1');

setTimeout(() => {
  console.log('2');
}, 0);

console.log('3');

Output:

1
3
2

Even with 0 milliseconds, the callback runs later.

[!warning] Warning
Async callbacks run after the current synchronous code finishes.


AJAX + API Flow

JavaScript app
   ↓
sends AJAX request
   ↓
API server
   ↓
sends JSON data
   ↓
JavaScript receives data
   ↓
page updates

Example:

User searches country
↓
JS requests country data
↓
API returns JSON
↓
JS displays country card

Quick Syntax Summary

setTimeout(callback, delay);
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));
const request = new XMLHttpRequest();

request.open('GET', url);
request.send();

Core Mental Model

Asynchronous JavaScript lets code keep running while waiting for slow tasks.

Start task
Continue code
Handle result later

AJAX means:

Get data from a server without reloading the page

API means:

A system that lets software communicate with other software

[!success] Remember
Async JS is about waiting without blocking.
AJAX is about requesting server data in the background.
APIs are the data sources your app talks to.