Fetch API and AJAX

Learn how to make HTTP requests and handle responses using modern web APIs.

Present State

Modern JavaScript applications heavily rely on server communication to fetch and send data. The Fetch API has become the standard way to make HTTP requests, replacing older AJAX techniques that used XMLHttpRequest. It provides a cleaner and more powerful promise-based syntax for handling asynchronous communication with APIs.

Code Example

Here's an example showing how to use the Fetch API to retrieve and post data:

Fetch API GET and POST

// GET Request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log('GET:', data))
  .catch(error => console.error('Error:', error));

// POST Request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'New Post',
    body: 'This is the post content',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log('POST:', data))
  .catch(error => console.error('Error:', error));
          

This code demonstrates:

  • Making HTTP GET and POST requests with fetch().
  • Using .then() to handle Promise-based responses.
  • Converting response to JSON with response.json().
  • Sending data with appropriate headers using POST.

Description

AJAX (Asynchronous JavaScript and XML) is a technique for making asynchronous web requests to update parts of a web page without refreshing.

The modern Fetch API simplifies AJAX by using promises. It's cleaner, more powerful, and supports the full suite of HTTP methods (GET, POST, PUT, DELETE, etc.).

  • fetch(url, options) initiates a request to the server.
  • Responses are returned as Promises and can be converted to JSON using response.json().
  • Headers and body content can be customized for POST/PUT requests.

Applications

  • Fetching data from RESTful APIs (e.g., posts, comments, user profiles).
  • Submitting form data asynchronously.
  • Creating interactive single-page applications (SPAs).
  • Loading content dynamically without page reloads.
  • Communicating with serverless backends or databases (e.g., Firebase).

Multiple Choice Questions

Q1: What does the Fetch API return?

  • A. String
  • B. Object
  • C. Promise
  • D. Array

Answer: C. Promise

Q2: Which method is used to parse a fetch response into JSON?

  • A. parseJSON()
  • B. response.text()
  • C. response.json()
  • D. JSON.parse()

Answer: C. response.json()

Q3: Which HTTP method is commonly used to submit form data?

  • A. GET
  • B. PUT
  • C. DELETE
  • D. POST

Answer: D. POST

Q4: What is one advantage of the Fetch API over XMLHttpRequest?

  • A. It uses JSON by default
  • B. It is synchronous
  • C. It returns promises
  • D. It supports only GET requests

Answer: C. It returns promises