Comprehensive Guide to XMLHttpRequest for Seamless API Interaction

Introduction to XMLHttpRequest (XHR)

The XMLHttpRequest (XHR) object is a vital part of web development, enabling the ability to make network requests to retrieve resources or communicate with servers, asynchronously if desired. This allows for the development of dynamic single-page applications (SPAs) and other interactive web experiences.

Basic Usage

  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://api.example.com/data', true);
  xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.responseText);
      }
  };
  xhr.send();

Sending Different Types of Requests

POST Request

  const xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://api.example.com/data', true);
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.responseText);
      }
  };
  xhr.send(JSON.stringify({ key: 'value' }));

PUT Request

  const xhr = new XMLHttpRequest();
  xhr.open('PUT', 'https://api.example.com/data/1', true);
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.responseText);
      }
  };
  xhr.send(JSON.stringify({ key: 'newValue' }));

DELETE Request

  const xhr = new XMLHttpRequest();
  xhr.open('DELETE', 'https://api.example.com/data/1', true);
  xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.responseText);
      }
  };
  xhr.send();

Handling Response Types

Setting the expected response type ensures that the data is handled correctly. Common response types are JSON, text, and document.

JSON Response

  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://api.example.com/data', true);
  xhr.responseType = 'json';
  xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.response);
      }
  };
  xhr.send();

Monitoring Progress

Using the progress event to monitor download progress.

  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://api.example.com/largefile', true);
  xhr.onprogress = function (event) {
      if (event.lengthComputable) {
          console.log(`Downloaded ${event.loaded} of ${event.total} bytes`);
      }
  };
  xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.responseText);
      }
  };
  xhr.send();

App Example Using XMLHttpRequest

Below is a simple example of a JavaScript application using XMLHttpRequest to fetch user data and display it on a web page.

  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>XHR Example</title>
  </head>
  <body>
      <h1>User Data</h1>
      <div id="user-data"></div>
      <script>
          const xhr = new XMLHttpRequest();
          xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true);
          xhr.onreadystatechange = function () {
              if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                  const users = JSON.parse(xhr.responseText);
                  const userDataDiv = document.getElementById('user-data');
                  users.forEach(user => {
                      const userDiv = document.createElement('div');
                      userDiv.innerHTML = `<strong>Name:</strong> ${user.name} <strong>Email:</strong> ${user.email}`;
                      userDataDiv.appendChild(userDiv);
                  });
              }
          };
          xhr.send();
      </script>
  </body>
  </html>

By understanding and implementing XMLHttpRequest, developers can build robust, interactive web applications that communicate seamlessly with servers.

Hash: bda35bc0c2610fb3f8cd2391549006fb2de7f7513c219b225bc57967b58d4b86

Leave a Reply

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