JavaScript Fetch API And AJAX Explained With Examples

JavaScript can request data from servers using AJAX and the modern Fetch API. These tools allow you to load data without refreshing the page, enabling dynamic and interactive web applications.

This blog explains how to use Fetch API and AJAX with examples.


1. What Is AJAX?

AJAX (Asynchronous JavaScript and XML) allows web pages to fetch data from a server asynchronously without reloading. Today, JSON is commonly used instead of XML.


2. Using Fetch API

The Fetch API is modern and promise-based. It simplifies sending requests and handling responses.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log("Error:", error));

Output (example):

{
  "userId": 1,
  "id": 1,
  "title": "Sample Title",
  "body": "Sample body text..."
}

3. Async/Await With Fetch

async function getPost() {
  try {
    let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    let data = await response.json();
    console.log(data);
  } catch(error) {
    console.log("Error:", error);
  }
}

getPost();

4. Sending Data With Fetch (POST Request)

async function createPost() {
  let response = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      title: "New Post",
      body: "This is a test post",
      userId: 1
    })
  });
  
  let data = await response.json();
  console.log(data);
}

createPost();

5. Why Use Fetch / AJAX

  • Update web page without reload
  • Create dynamic and responsive apps
  • Handle API calls efficiently
  • Works well with JSON data

Conclusion

The Fetch API and AJAX are essential tools for modern web development. They enable asynchronous data fetching, allowing developers to create smooth and interactive user experiences without reloading the page.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *