Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

Ajax

Tutorials – Ajax

 
Chapter 6: Fetch API in Ajax

 

The Fetch API has become a modern and preferred alternative to XMLHttpRequest for making asynchronous requests in web development. It provides a cleaner and more powerful interface for fetching resources from a server. In this chapter, we will explore the Fetch API, its features, and best practices for using it effectively in Ajax applications.


Introduction to the Fetch API

The Fetch API is a web API that allows you to make network requests, such as fetching data from a server, without the need for a page reload. It is more versatile and developer-friendly than the traditional XMLHttpRequest. The Fetch API returns Promises, which simplifies asynchronous programming and error handling.

One of the main advantages of the Fetch API is its native support for Promises, making it easier to work with asynchronous code. Promises provide a cleaner and more organized way to manage and respond to asynchronous events, such as fetching data from a server.


Making a Simple GET Request

The Fetch API is straightforward to use for making GET requests. Here’s how to create a basic GET request:

fetch('https://api.example.com/data')
  .then(function (response) {
    if (!response.ok) {
      throw new Error('Request failed with status: ' + response.status);
    }
    return response.text(); // or response.json() for JSON data
  })
  .then(function (data) {
    // Process and use the retrieved data
  })
  .catch(function (error) {
    console.error(error);
  });

In this example:

  • We use the fetch function to initiate a GET request to the specified URL.
  • The fetch function returns a Promise that resolves with the Response object representing the response to the request.
  • We check if the response status is in the 200-299 range (indicating a successful response).
  • We use response.text() to retrieve the response data as text. If you expect JSON data, use response.json() instead.
  • Finally, we handle errors by catching any exceptions.

Sending Data with a POST Request

The Fetch API makes it easy to send data with a POST request. Here’s an example of making a POST request:

fetch('https://api.example.com/update', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    key1: 'value1',
    key2: 'value2',
  }),
})
  .then(function (response) {
    if (!response.ok) {
      throw new Error('Request failed with status: ' + response.status);
    }
    return response.text();
  })
  .then(function (data) {
    // Process and use the response data
  })
  .catch(function (error) {
    console.error(error);
  });

In this example:

  • We specify the HTTP method as ‘POST’ and set the Content-Type header to indicate that we are sending JSON data.
  • The data to be sent is included in the body property as a JSON string, created using JSON.stringify().
  • We handle the response and errors in the same way as in the previous example.


Handling Responses

The Fetch API simplifies handling responses. You can use methods like response.text() or response.json() to parse the response data. Here’s an example of handling a JSON response:

fetch('https://api.example.com/data')
  .then(function (response) {
    if (!response.ok) {
      throw new Error('Request failed with status: ' + response.status);
    }
    return response.json(); // Parsing the response as JSON
  })
  .then(function (data) {
    // Process and use the response data
  })
  .catch(function (error) {
    console.error(error);
  });

In this example, we use response.json() to parse the response as JSON data. If you expect plain text, you can use response.text().


Error Handling

Handling errors is crucial in any network request. The Fetch API provides a straightforward way to handle errors using Promises. By checking the response.ok property, you can quickly identify successful and unsuccessful responses. For non-200 status codes, you can throw an error to trigger the catch block.

fetch('https://api.example.com/data')
  .then(function (response) {
    if (!response.ok) {
      throw new Error('Request failed with status: ' + response.status);
    }
    return response.json();
  })
  .then(function (data) {
    // Process and use the response data
  })
  .catch(function (error) {
    console.error(error);
  });

In this example, we throw an error if the response status is not in the 200-299 range. This error is caught in the catch block, allowing you to handle the error gracefully.


Aborting Requests

The Fetch API provides a way to abort requests by using the AbortController and AbortSignal objects. This is especially useful for canceling ongoing requests when necessary, such as when a user decides to cancel a long-running operation.

Here’s how you can use AbortController to cancel a request:

const abortController = new AbortController();
fetch('https://api.example.com/data', { signal: abortController.signal })
  .then(function (response) {
    if (!response.ok) {
      throw new Error('Request failed with status: ' + response.status);
    }
    return response.json();
  })
  .then(function (data) {
    // Process and use the response data
  })
  .catch(function (error) {
    if (error.name === 'AbortError') {
      console.warn('Request was aborted by the user.');
    } else {
      console.error(error);
    }
  });
// To abort the request after a timeout or based on user action:
// abortController.abort();

In this example, we create an AbortController and pass its signal property to the fetch request. To abort the request, call abortController.abort().


Security and Same-Origin Policy

The same-origin policy applies to the Fetch API, just as it does to XMLHttpRequest. This policy restricts web pages from making requests to a different domain (origin) than the one that served the web page.

To work around the same-origin policy, you can use techniques like Cross-Origin Resource Sharing (CORS) or JSONP. These techniques enable cross-origin requests but come with their own security considerations.


Best Practices

When working with the Fetch API, consider the following best practices:

  1. Use Promises: Take full advantage of the Promises returned by the Fetch API to simplify asynchronous code and error handling.
  2. Error Handling: Always implement error handling to gracefully handle network errors, timeouts, and non-200 status codes.
  3. Security: Be aware of the same-origin policy and use CORS or other techniques to enable cross-origin requests when necessary.
  4. Aborting Requests: Provide a way to cancel or abort ongoing requests, especially for long-running operations.
  5. Testing: Test your Fetch-based functionality thoroughly to ensure it works as expected and handles errors gracefully.
  6. Security Headers: Consider including security headers in your responses, such as Content Security Policy (CSP), to protect your web application from potential security vulnerabilities.


Conclusion

The Fetch API has brought significant improvements to making asynchronous requests in web development. Its native support for Promises simplifies handling asynchronous operations and error management. By using the Fetch API effectively, you can streamline data retrieval and interaction with web servers. In the next chapter, we will delve into more advanced topics in the world of Ajax, including working with different data formats, error handling, and interacting with third-party APIs.

Scroll to Top