JAVASCRIPT Tutorial

XMLHttpRequest Object

Introduction

The XMLHttpRequest (XHR) object is a fundamental tool for web development, enabling asynchronous data transfer between a web page and a server. It plays a crucial role in AJAX (Asynchronous JavaScript and XML), a technique used to create dynamic and interactive web applications.

Key Concepts

  • XMLHttpRequest: An object used to send HTTP requests and receive responses from a server.
  • HTTP Request: A message sent from the client (web browser) to the server, specifying the action to be performed (e.g., GET, POST).
  • HTTP Response: A message sent from the server to the client, containing the requested data or an error message.
  • Data Transfer: XHR allows for the transfer of data in various formats, such as text, XML, JSON, or binary data.
  • Asynchronous Operations: XHR operations are asynchronous, meaning that the browser can continue executing other tasks while it waits for the response from the server.

Sending an HTTP Request

  1. Create an XMLHttpRequest object:
let xhr = new XMLHttpRequest();
  1. Open the request:
xhr.open("GET", "data.txt");
  • "GET" specifies the type of request (in this case, getting data).
  • "data.txt" is the URL of the server resource to be accessed.
  1. Send the request:
xhr.send();

Receiving and Handling the Response

  1. Implement an event handler for the "readystatechange" event:
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      console.log(xhr.responseText);
    } else {
      console.error("Error: " + xhr.status);
    }
  }
};
  • "xhr.readyState" indicates the current state of the request.
  • "xhr.status" contains the HTTP status code of the response.
  • "xhr.responseText" contains the response data.

Example: Exploring the XMLHttpRequest Object

The following JavaScript code demonstrates the use of the XMLHttpRequest object:

const xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt");
xhr.send();

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      document.getElementById("response").innerHTML = xhr.responseText;
    } else {
      console.error("Error: " + xhr.status);
    }
  }
};

This code creates an XMLHttpRequest object, sends a GET request to a text file, and displays the response in an HTML element with the ID "response".

Conclusion

The XMLHttpRequest object is a powerful tool for data exchange between web pages and servers. It enables the creation of dynamic and interactive applications without requiring full page reloads. Understanding the concepts and practical steps outlined in this guide will empower developers to effectively utilize XHR in their web development projects.