XMLHttpRequest API - Web API Reference

Introduction

The XMLHttpRequest API provides a way to create XMLHttpRequest objects, which allow you to send HTTP requests asynchronously from JavaScript.

This API allows you to make AJAX (Asynchronous JavaScript and XML) requests to servers without having to re-load the entire page. You can use this API to perform actions such as:

Usage

                const xhr = new XMLHttpRequest();
                xhr.open('GET', '/data');
                xhr.onreadystatechange = function () {
                    if (xhr.status === 200) {
                        console.log(xhr.responseText);
                    }
                };
                xhr.send();
            

This example demonstrates how to create an XMLHttpRequest object, open a request, and handle the response.

Properties

open(method, url) - Opens a connection to the specified URL with the given method (GET/POST).
send(data) - Sends the request data.
readyState - Indicates the state of the request.

Events

onreadystatechange - Fires when the readyState changes.
onprogress - Fires during the progress of the request.

Examples

Simple GET Request

                    const xhr = new XMLHttpRequest();
                    xhr.open('GET', '/data');
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            console.log(xhr.responseText);
                        }
                    };
                    xhr.send();
                

Simple POST Request

                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', '/data');
                    xhr.setRequestHeader("Content-Type", "application/json");
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            console.log(xhr.responseText);
                        }
                    };
                    xhr.send(JSON.stringify({ key: 'value' }));
                

Notes

Note: The XMLHTTPRequest API is supported in all modern browsers.
Note: When making a request, ensure you handle CORS properly.