Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

AJAX and Fetch API

AJAX and Fetch API

AJAX (Asynchronous JavaScript and XML) and the Fetch API are powerful tools in web development for making asynchronous requests to servers, retrieving data, and updating the DOM without the need for a page refresh. Here's an introduction to AJAX and the Fetch API:

AJAX (Asynchronous JavaScript and XML):

AJAX allows you to send and receive data from a server asynchronously without reloading the entire page. It can be used to fetch data, send data, and update parts of a webpage.

Creating an XMLHttpRequest Object:

let xhr = new XMLHttpRequest();
 

Making a GET Request:

xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      let responseData = JSON.parse(xhr.responseText);
      console.log(responseData);
    } else {
      console.error('Error:', xhr.status);
    }
  }
};
xhr.send();
 

Fetch API:

The Fetch API is a modern replacement for XMLHttpRequest that provides a simpler and more powerful way to make network requests.

Making a GET Request:

fetch('https://api.example.com/data')
  .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:', error);
  });
 

Sending Data with Fetch:

Making a POST Request:

fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John Doe', email: 'john@example.com' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
 

Fetch Options:

  • method: Specifies the HTTP method (GET, POST, PUT, DELETE, etc.).
  • headers: Specifies request headers.
  • body: Contains the data to send (for POST, PUT requests).
  • mode: Controls the CORS (Cross-Origin Resource Sharing) policy.
  • credentials: Sets whether to include credentials like cookies.
  • cache: Controls caching behavior.
  • redirect: Sets follow behavior (manual, follow, error).
  • timeout: Sets the request timeout (in milliseconds).

Handling Responses:

  • The response.ok property indicates if the response was successful (status in the range 200-299).
  • The response.json() method parses the response body as JSON.
  • The response.text() method retrieves the response as text.