8 minutes read

XMLHttpRequests are objects used to interact with the server. It retrieves data from the URL without refreshing the website. The website updates just in part without disrupting user activity. AJAX programming heavily relies on XMLHttpRequest. Despite the name, XMLHttpRequest can also retrieve any data type, not just XML. The XMLHttpRequest() method constructs a new XMLHttpRequest. Before using any method, remember to call the constructor.

XMLHttpRequest properties

In this part, we will cover the XMLHttpRequest properties. The properties, along with the explanation, are listed down below:

  • XMLHttpRequest.readyState returns the state of the XMLHttpRequest client.

  • XMLHttpRequest.response returns the body content of the response as a value depending on the responseType property of the request.

  • XMLHttpRequest.responseText returns the text received from the server following the request sent.

  • XMLHttpRequest.responseType enumerates string value specifying the type of data contained in the response.

  • XMLHttpRequest.responseURL returns the URL of the response or an empty string if the URL is null.

  • XMLHttpRequest.responseXML returns a document containing the HTML or XML retrieved by request.

  • XMLHttpRequest.status returns the numerical HTTP status code of the XMLHttpRequest response.

XMLHttpRequest methods

In this part, we will cover basic XMLHttpRequest methods so that you understand the usage of some of them in the XMLHttpRequest usage section. The methods, along with the explanation, are listed down below:

  • XMLHttpRequest.abort() is used for aborting the request if it has already been sent.

  • XMLHttpRequest.open() initializes a newly-created request, or re-initializes an existing one.

  • XMLHttpRequest.send() sends the request. The method will return asynchronous requests as soon as the request is sent.

  • XMLHttpRequest.getAllResponseHeaders() returns all response headers as a string value or returns null if there is no response.

  • XMLHttpRequest.getResponseHeader() returns a string containing the text of a particular header's value.

  • XMLHttpRequest.setRequestHeader() sets the value of an HTTP request header. Use it before the open() and send() methods.

  • XMLHttpRequest.overrideMimeType() overrides the MIME type that the server returns.

XMLHttpRequest Events

Before we take a look at an example of an XMLHttpRequest, let's see what events we can use. Here is the list of these events:

  • abort — the request has been aborted;

  • error — the request encountered an error;

  • load — the XMLHttpRequest transaction is completed successfully;

  • loadend — the request is complete;

  • loadstart — the request started to load data;

  • progress — the request periodically requests data;

  • readystatechange — the readyState property changes;

  • timeout — the progress is terminated.

XMLHttpRequest usage

In this part, you will learn how to use XMLHttpRequest to issue HTTP requests to exchange data between the website and a server. First, you need to create an XMLHttpRequest object to create an HTTP request, open a URL, and send the request. The XMLHttpRequest object is used to request data from the web server. Thanks to the XMLHttpRequest object, you can:

  • retrieve data from the URL without refreshing the website;

  • request and receive the data from a server after the page has loaded;

  • send the data to a server in the background.

After the completed transaction, the object will hold valuable information, for instance, the response body and the HTTP status of the result. Let's go through one example line by line.

First, we will create a function requestListener that returns the text received from a server following a request:

function requestListener () {
  console.log(this.responseText);
}

Then, we create an XMLHttpRequest object to create an HTTP request. We will create a new object and store it in the request variable:

const request = new XMLHttpRequest();

After that, the method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. In this case, the target is a request object. load is an event that will send when an XMLHttpRequest transaction completes successfully.

request.addEventListener("load", requestListener);

The method open() initializes a newly-created request, or re-initializes an existing one, and GET retrieves the data.

request.open("GET", "https://api.github.com/users/alabak48");

Finally, the method send() will send the request to the server.

request.send();

In the snippet below you can see the entire code. Note that we placed the function on the clickable button:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>Using the XMLHttpRequest Object</h2>

<div id="demo">
<button type="button" onclick="requestListener()">Change Content</button>
</div>

<script>
function requestListener () {
  console.log(this.responseText);
}

const request = new XMLHttpRequest();
request.addEventListener("load", requestListener);
request.open("GET", "https://api.github.com/users/alabak48");
request.send();
</script>
</body>
</html>

In this example, we used this link. If you have a GitHub account you can replace it with your username. This function will output all the information about the GitHub user that is publicly available. Here is the code output:

{
  "login": "alabak48",
  "id": 79693733,
  "node_id": "MDQ6VXNlcjc5NjkzNzMz",
  "avatar_url": "https://avatars.githubusercontent.com/u/79693733?v=4",
  "gravatar_id": "",
  "url": "https://api.github.com/users/alabak48",
  "html_url": "https://github.com/alabak48",
  "followers_url": "https://api.github.com/users/alabak48/followers",
  "following_url": "https://api.github.com/users/alabak48/following{/other_user}",
  "gists_url": "https://api.github.com/users/alabak48/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/alabak48/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/alabak48/subscriptions",
  "organizations_url": "https://api.github.com/users/alabak48/orgs",
  "repos_url": "https://api.github.com/users/alabak48/repos",
  "events_url": "https://api.github.com/users/alabak48/events{/privacy}",
  "received_events_url": "https://api.github.com/users/alabak48/received_events",
  "type": "User",
  "site_admin": false,
  "name": "Anja",
  "company": "https://www.jetbrains.com/academy/",
  "blog": "",
  "location": "Osijek",
  "email": null,
  "hireable": null,
  "bio": "IT student 🖥️  \r\nPart of the Frontend course team at JetBrains Academy \r\n",
  "twitter_username": null,
  "public_repos": 8,
  "public_gists": 0,
  "followers": 4,
  "following": 5,
  "created_at": "2021-02-26T09:35:38Z",
  "updated_at": "2022-09-18T16:17:33Z"
}

Conclusion

To sum up, in this topic, you learned what XMLHttpRequest is. You learned about different properties, methods, and events of XMLHttpRequest.

In the end, we went through some usage examples to see the XMLHttpRequest in action. Let's practice now with the tasks!

29 learners liked this piece of theory. 5 didn't like it. What about you?
Report a typo