XMLHttpRequest is a built-in browser object that allows to make HTTP requests in JavaScript.
Despite of having the word “XML” in its name, it can operate on any data, not only in XML format. We can upload/download files, track progress and much more.
Right now, there’s another, more modern method fetch, that somewhat deprecates XMLHttpRequest.
In modern web-development XMLHttpRequest is used for three reasons:
- Historical reasons: we need to support existing scripts with
XMLHttpRequest. - We need to support old browsers, and don’t want polyfills (e.g. to keep scripts tiny).
- We need something that
fetchcan’t do yet, e.g. to track upload progress.
Does that sound familiar? If yes, then all right, go on with XMLHttpRequest. Otherwise, please head on to fetch.
The basics
XMLHttpRequest has two modes of operation: synchronous and asynchronous.
Let’s see the asynchronous first, as it’s used in the majority of cases.
To do the request, we need 3 steps:
-
Create
XMLHttpRequest:let xhr = new XMLHttpRequest();The constructor has no arguments.
-
Initialize it, usually right after
new XMLHttpRequest:xhr.open(method, URL, [async, user, password])This method specifies the main parameters of the request:
method– HTTP-method. Usually"GET"or"POST".URL– the URL to request, a string, can be URL object.async– if explicitly set tofalse, then the request is synchronous, we’ll cover that a bit later.user,password– login and password for basic HTTP auth (if required).
Please note that
opencall, contrary to its name, does not open the connection. It only configures the request, but the network activity only starts with the call ofsend. -
Send it out.
xhr.send([body])This method opens the connection and sends the request to server. The optional
bodyparameter contains the request body.Some request methods like
GETdo not have a body. And some of them likePOSTusebodyto send the data to the server. We’ll see examples of that later.