ZetCode

XMLHttpRequest tutorial

last modified 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.

fetch_time.js
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.

index.html
<!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.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all JavaScript tutorials.

AltStyle によって変換されたページ (->オリジナル) /