INTRODUCTION TO FETCH API AND AJAX FOR DYNAMIC CONTENT
Introduction to Fetch API and AJAX for Dynamic Content
What is AJAX?
AJAX stands for Asynchronous JavaScript and XML. It's a technique used in web development to
send and receive data from a server asynchronously without having to reload the whole web
page.
It Improves the user experience by enabling partial page updates.
It Used XML for data exchange (hence the name), but today JSON is more common.
Key Concepts of AJAX
Asynchronous: Doesn't block other operations while waiting for a response.
Dynamic: Allows updating parts of a web page dynamically.
APIs used: XMLHttpRequest (old), Fetch API (modern)
Example:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
xhr.onload = function () {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error('Error:', xhr.status);
};
xhr.send();
Drawbacks:
Verbose syntax
Harder to read and maintain
No built-in support for Promises
Fetch API
introduction to Fetch API
The Fetch API is a modern way to make HTTP requests (like GET, POST, PUT, DELETE) in
JavaScript. It is used to send or retrieve data from a server, such as APIs, databases, or
backends.
Why Use Fetch API?
Built into modern browsers (no need to install anything)
Easier and cleaner than older methods like XMLHttpRequest
Uses Promises, which are simpler than callbacks
Basic Syntax
fetch(url, options)
.then(response => response.json())
.then(data => {
// Use the data
})
.catch(error => {
// Handle errors
});
url: The address you're sending a request to (e.g., an API endpoint)
options: Optional settings like method, headers, body, etc.
Example 1: GET Request (Fetch Data)
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => {
console.log(data); // Shows the fetched data
})
.catch(error => {
console.error('Error:', error);
});
Example 2: POST Request (Send Data)
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Alice',
email: '[email protected]'
})
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
Key Concepts
GET - Retrieve data
POST - Send new data
PUT - Update existing data
DELETE - Remove data
response.json() - Converts the response into a JavaScript object
JSON.stringify() - Converts JavaScript object into a JSON string for sending