XMLHttpRequest tutorial
last modified October 18, 2023
In this article we show how to make HTTP request in JavaScript with XMLHttpRequest.
XMLHttpRequest
XMLHttpRequest is a built-in browser object that allows to make HTTP requests in JavaScript. XMLHttpRequest API provides client functionality for transferring data between a client and a server. It allows an easy way to retrieve data from a URL without having to do a full page refresh.
As a consequence, a web page has to update just a part of the page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming. XMLHttpRequest works in two modes of operation: synchronous and asynchronous. Despite its name, XMLHttpRequest can operate on any data, not only XML.
XMLHttpRequest example
The following example creates a request to a testing site and returns the current datetime.
let getJSON = (url, callback) => { let xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = () => { let status = xhr.status; if (status == 200) { callback(null, xhr.response); } else { callback(status); } }; xhr.send(); }; getJSON('http://time.jsontest.com', (err, data) => { if (err != null) { console.error(err); } else { let text = `Date: ${data.date} Time: ${data.time} Unix time: ${data.milliseconds_since_epoch}` console.log(text); } });
This example reads JSON data with XMLHttpRequest
.
let xhr = new XMLHttpRequest();
A new instance of XMLHttpRequest
is created.
xhr.open('GET', url, true);
The open
method initializes a GET request to the specified URL. The
third parameter true
makes it an asynchronous request.
xhr.responseType = 'json';
The responseType
value defines the response type.
xhr.onload = function() { var status = xhr.status; if (status == 200) { callback(null, xhr.response); } else { callback(status); } };
Inside the onload
method, we wait for the response from the server.
xhr.send();
The send
method sends the request; the request is asynchronous by
default.
let text = `Date: ${data.date} Time: ${data.time} Unix time: ${data.milliseconds_since_epoch}` console.log(text);
We log the date, time, and the Unix time to the console.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Consume XML request</title> <script src="fetch_time.js"></script> </head> <body> </body> </html>
The code is loaded into HTML page. After we load the page in the browser, we go to the browser console, which is available in developer tools.
Source
XMLHttpRequest - language reference
In this article we have created a HTTP request in JavaScript with XMLHttpRequest.