Hey everyone in this article we will learn about what is XMLHttpRequest (XHR) in Javascript and how you can use it in your web application to load content dynamically without refreshing the whole page .

If you want to use AJAX in your web application, then it is very important to know about XMLHttpRequest.

So before moving forward to XHR, let’s have a brief about AJAX!

AJAX: Asynchronous JavaScript and XML

Asynchronous means we aren’t making blocking calls. It means our calls are running in background thus the DOM rendering doesn’t gets blocked.

Most of the programming languages we use today are synchronous which means they make blocking calls i.e. the next line of code isn’t executed until the previous line of code has done execution.

AJAX is not a programming language. Rather, it’s a set of existing technologies.

AJAX helps in fetching data asynchronously without inferring with the existing page. It means “No page reload/refresh”.

Modern websites use JSON instead of XML for data transfer.

Why use AJAX?

No page reload/refresh.

Better user experience

Saves network bandwidth

Very interactive

How it works?

AJAX uses XMLHttpRequest object (also called xhr object) to achieve this.

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.

XMLHttpRequest(XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate data to and from a web server using HTTP, establishing an independent connection between Client and Server.

This xhr object contains a variety of methods and utility functions using which we can make AJAX calls. It is an inbuilt function in JS. No need to import any framework or library. It is used for asynchronous communication between client and server.
It performs following operations:
• Sends data from client in the background
• Receives data from the server
• Updates the webpage without reloading it.

const variable = new XMLHttpRequest();

Data can be transferred in any format(Text data, XML data & JSON data) and protocol.

NOTE: It’s depreciated now so we aren’t going in depth of it in this article!

XMLHttpRequest Properties

• XMLHttpRequest.readyState
Returns a number representing the state of the request.

Returns an ArrayBuffer, a Blob, a Document, a JavaScript object, or a string, depending on the value of XMLHttpRequest.responseType, that contains the response entity body.

Returns a string that contains the response to the request as text from a server, or null if the request was unsuccessful or has not yet been sent.

Specifies the type of the response.
It is an enumerated string value specifying the type of data contained in the response. It also lets the author change the response type.
If an empty string is set as the value of responseType, the default value of text is used.

— “”- An empty responseType string is treated the same as “text”, the default type.
 arraybuffer- The response is a JavaScript ArrayBuffer containing binary data.
— blob- The response is a Blob object containing the binary data.
 document- The response is an HTML document or XML document, as appropriate based on the MIME type of the received data
 json- The response is a JavaScript object created by parsing the contents of received data as JSON.
— text- The response is a text in a DOMString object.

Returns the serialized URL of the response or the empty string if the URL is null.

Returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in Web Workers.

Returns the HTTP response status code of the request.

Returns a string containing the response string returned by the HTTP server. Unlike XMLHttpRequest.status, this includes the entire text of the response message (“OK”, for example).

The time in milliseconds a request can take before automatically being terminated.

A XMLHttpRequestUpload representing the upload process.

Returns true if cross-site Access-Control requests should be made using credentials such as cookies or authorization headers; otherwise false.


XMLHttpRequest Methods

open(method,url,async,user,psw)– This method is used to initialise a newly-created request, or re-initialises an existing one.

method: the request type GET,POST or HEAD or another method supported by server.

url: The URL/File location you are sending the request to. This can be a .txt, .xml, .asp, .jsp, .php files etc.

async: If asynchronous then it take ttue or if synchronous then it take false. By default it is true.

user: User name to use for authentication purpose. By default it is null. It is optional.

pwd: Password to use for authentication purpose. By default it is null. It is optional.

xhr.open(“GET”, ‘data.txt’, true);

send()– This method is used to send the request to server. This is used for GET requests.

send(body)– This method is used to send the request to the server. This is used for POST requests. Where body is the data you want to send.

setRequestHeader(header, value)– This method is used to Add a header-value pair to the header to be sent.
xhr.setRequestHeader(“Access-Control-Allow-Origin”, “*”)

getResponseHeader(headerName)– This method returns specific header information from the server response.

getAllResponseHeaders()– This method returns all haeder information from the server response.

abort()– This method is used to cancel the current request. When a request is aborted, its readyState is changed to XMLHttpRequest.UNSENT(0) and request’s status code is set to 0.

Let’s understand all this better by few examples:

Index.html : This page contains the boilerplate take from getbootstrap.com where i’ve initialsed two buttons named fetch and backup.

Output Screen

Explaination: upon pressing the fetch button we get the desried output. Since we have pressed the fetch button and to track its progress we have attached an onprogress eventthus the first thing to get printed on the console is “on progress”. Followed by the text in the bepractical.txt.

Have you thought, what will happen if we give a file name that doesn’t exists?

Here’s the output!


To avoid such kinds of errors and print something relative to the error we have used the status codes in the onload function to check for good and bad status codes and throw output on the console accordingly.


Here’s the output now!


To read more about status codes: HTTP response status codes — HTTP | MDN (mozilla.org)

Before concluding the article, let’s go through one more interesting thing.


Tried printing a statement at the end of index.js.


But woah? what’s the output??
It gets printed first?

Have you figured it out?
If NO, then let me tell you!
Since we have used async as true, it won’t take blocking calls thus gives the output as seen above!

Hope you enjoyed the article.
Follow for more!

With love | Janhvi Singh @BePractical .

For more details, visit the official documentation: XMLHttpRequest — Web APIs | MDN (mozilla.org)