Jump to content

Featured Replies

Posted

You are reading Part 20 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]

Introduction

AJAX (Asynchronous JavaScript and XML) allows web applications to send and receive data from a server asynchronously, without requiring a page reload. Modern JavaScript uses the fetch() API or the older XMLHttpRequest to handle HTTP requests.

AJAX, powered by JavaScript and the fetch() API, allows modern web applications to interact with servers asynchronously. Understanding HTTP methods (GET, POST, PUT, DELETE) is essential for handling API requests effectively. Mastering these concepts ensures efficient and structured communication between front-end applications and back-end services.

HTTP methods define how requests interact with resources on a server. The most commonly used HTTP methods are GET, POST, PUT, and DELETE.

1. Making HTTP Requests with fetch()

The fetch() API provides a cleaner way to handle HTTP requests compared to XMLHttpRequest. It returns a Promise that resolves to the Response object.

Basic Syntax:

fetch(url, options)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));
  • url: The API endpoint.

  • options (optional): An object containing HTTP method, headers, and body.

2. HTTP GET Request

A GET request retrieves data from a server. It does not modify any data on the server.

Example: Fetching Data with GET

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

Expected Output:

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

3. HTTP POST Request

A POST request sends new data to the server.

Example: Creating Data with POST

fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        title: "New Post",
        body: "This is a new post.",
        userId: 1
    })
})
.then(response => response.json())
.then(data => console.log("Post Created:", data))
.catch(error => console.error("Error posting data:", error));

Expected Output:

{
  "title": "New Post",
  "body": "This is a new post.",
  "userId": 1,
  "id": 101
}

4. HTTP PUT Request

A PUT request updates an existing resource on the server.

Example: Updating Data with PUT

fetch("https://jsonplaceholder.typicode.com/posts/1", {
    method: "PUT",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        title: "Updated Post",
        body: "This post has been updated.",
        userId: 1
    })
})
.then(response => response.json())
.then(data => console.log("Post Updated:", data))
.catch(error => console.error("Error updating data:", error));

5. HTTP DELETE Request

A DELETE request removes a resource from the server.

Example: Deleting Data with DELETE

fetch("https://jsonplaceholder.typicode.com/posts/1", {
    method: "DELETE"
})
.then(response => {
    if (response.ok) {
        console.log("Post deleted successfully");
    }
})
.catch(error => console.error("Error deleting data:", error));

6. Handling Errors and Status Codes

Always check the response status before processing data to ensure the request was successful.

Example:

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error("Error fetching data:", error.message));

7. When to Use Each HTTP Method

HTTP Method

Purpose

GET

Retrieve data from the server

POST

Create new resources on the server

PUT

Update an existing resource

DELETE

Remove a resource from the server

You are reading Part 20 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]

  • Views 34
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.