What is XMLHttpRequest in JavaScript? How does it work?

XMLHttpRequest (often abbreviated as XHR) is an API in JavaScript used for making HTTP requests to servers without refreshing the page. This is commonly used in AJAX (Asynchronous JavaScript and XML) operations to fetch data from a server and dynamically update parts of a web page.

Key Features of XMLHttpRequest

  1. Asynchronous Communication: Allows sending and receiving data without blocking the web page's user interface.
  2. Supports Different HTTP Methods: Can send requests using various HTTP methods such as GET, POST, PUT, DELETE, etc.
  3. Handles Different Data Formats: Can work with different data formats including XML, JSON, HTML, and plain text.

Creating an XMLHttpRequest Object

Here’s a step-by-step guide to creating and using an XMLHttpRequest object:

Create an XMLHttpRequest Object:

var xhr = new XMLHttpRequest();

Configure the Request:

  • Open the request by specifying the HTTP method and URL. Optionally, you can specify whether the request is asynchronous (true by default).
xhr.open('GET', 'https://api.example.com/data', true);

Set Request Headers (Optional):

  • If you need to set custom headers, you can do so using `setRequestHeader`.
xhr.setRequestHeader('Content-Type', 'application/json');

Define a Callback Function:

  • Assign a function to the `onreadystatechange` event to handle the response when the ready state changes.
xhr.onreadystatechange = function () {
    if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
            // Successful response
            console.log(xhr.responseText);
        } else {
            // Handle error
            console.error('Error:', xhr.statusText);
        }
    }
};

Send the Request:

  • For GET requests, simply call `send` without any arguments. For POST or other methods, you might need to pass the request body.
xhr.send();

Complete Example

Here is a complete example of making a GET request using XMLHttpRequest:

// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure it: GET-request for the URL /article/.../load
xhr.open('GET', 'https://api.example.com/data', true);

// Optional: Add request headers
xhr.setRequestHeader('Content-Type', 'application/json');

// Define what to do when the response arrives
xhr.onreadystatechange = function () {
    if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
            // Successful response
            console.log('Response:', xhr.responseText);
        } else {
            // Handle error
            console.error('Error:', xhr.statusText);
        }
    }
};

// Send the request
xhr.send();

Understanding readyState and status

  • `readyState`:
  • `0` (UNSENT): Client has been created. `open()` not called yet.
  • `1` (OPENED): `open()` has been called.
  • `2` (HEADERS_RECEIVED): `send()` has been called, and headers and status are available.
  • `3` (LOADING): Downloading; `responseText` holds partial data.
  • `4` (DONE): The operation is complete.
  • status:
  • `200`: OK (successful response).
  • `404`: Not Found.
  • Other standard HTTP status codes.

Asynchronous vs. Synchronous Requests

  • Asynchronous: Does not block the execution of subsequent JavaScript. Preferred for most use cases.
  • Synchronous: Blocks the execution until the response is received. This can make the web page unresponsive and is generally discouraged.

Using XMLHttpRequest allows web applications to communicate with servers in the background, enhancing user experience by making web applications faster and more responsive.

Further, if you have any questions, please visit our websiteGurulabs Website Design Agency.