DEV Community

Adam Roynon
Adam Roynon

Posted on

XMLHttpRequest in JavaScript

XMLHttpRequest is an object in JavaScript that allows you to send AJAX requests to the server, it allows you to get a response from the server using an asynchronous process. Asynchronous calls allow you to get a response from the server without having to reload the page. Imagine a social media website that automatically/dynamically updates your feed without you having to reload the page or tells you there are new posts available for you to update. This is an example of how AJAX can asynchronous server calls can be used.

The below code shows a basic XMLHttpRequest in JavaScript. First, you need to create a new XMLHttpRequest object using the 'new' keyword. Then we modify its 'onreadystatechange' event to log out the response from the request to the developer console. Within this event, there is an if statement that checks the 'readyState' and 'status' fields of the XMLHttpRequest object, these two checks ensures that the request is completed and has been successful. After we then call the 'open' function on the object and give it a request method of "GET" and a file we want to access on the server. Finally, we send the request. Opening and sending the request and similar to like opening your phone app, or phonebook, and then actually making a phone call. For this example, the contents of the text file "my_info.txt" will be returned and printed to the developer console.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};
xhttp.open("GET", "my_info.txt", true);
xhttp.send();
Enter fullscreen mode Exit fullscreen mode

You can also send a request to a PHP file too. The PHP file could include some sort of process you want to execute, such as retrieving information from the database. When we request a server-side script, such as a PHP file, the file will be executed and its result will be returned to our AJAX request. Imagine the contents of the 'ajax_request.php' included getting some information from the database and then printing that information, this process will then be executed and printed to the file contents, then similarly to the previous example the contents of this file will be returned and printed to the developer console.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};
xhttp.open("GET", "ajax_request.php", true);
xhttp.send();
Enter fullscreen mode Exit fullscreen mode

Using an XMLHttpRequest you can also send information to the server. You may need/want to do this when sending data to the server to be processed on the database or on a server-side process. For example, we could create an object that contains some data we wish to send to the server.

var data = {
  id: 13,
  name: "John Smith",
  age: 34
}
Enter fullscreen mode Exit fullscreen mode

The below example shows an example of an XMLHttpRequest that sends data to an endpoint. Instead of sending the request using a 'GET' method it uses a 'POST' method, and sends the request to an endpoint called '/adduser'. The variable called 'data' is sent on the request by passing it into the send function. This will send the data to the endpoint and return the response in the 'onreadystatechange' event listener.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};
xhttp.open("POST", "/addUser", true);
xhttp.send(data);
Enter fullscreen mode Exit fullscreen mode

This post was originally published on https://acroynon.com/

Top comments (12)

Collapse
 
artemtam profile image
Artem Tamoian

It's 2020, use promise-based fetch() instead.

Collapse
 
acroynon profile image
Adam Roynon

I agree that you there are better solutions now. It's always good to refresh on the underlying principles and workings though

Collapse
 
artemtam profile image
Artem Tamoian • Edited

Is using var and non-strict equality (==) a part of refreshing on the underlying principles?

Thread Thread
 
acroynon profile image
Adam Roynon

Using var is fine for these examples as it is block scoped. I could have use the new let/const keywords plus non-strict equality, etc, etc. But for just showing the basics of XMLHttpRequest they're not needed and it would have over complicated the simple examples.

Thread Thread
 
artemtam profile image
Artem Tamoian

There's no point in using legacy and problematic syntax such as var and ==. For beginners, it makes sense to show correct examples of modern JavaScript. We don't speak Old Slavonic teaching kids Russian, so why should we use the legacy syntax when teaching people how to code?

Thread Thread
 
artemtam profile image
Artem Tamoian

The last example is even incorrect, XMLHttpRequest will not do JSON.stringify() automatically for you. Try running this code in the console:

var data = {
  id: 13,
  name: "John Smith",
  age: 34
}

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};

xhttp.open("POST", "/addUser", true);
xhttp.send(data);

It sends [object Object] instead of JSON you expect.

Thread Thread
 
acroynon profile image
Adam Roynon

As you have pointed out, a more modern approach to this problem is to use a library such as axios. However, some people (not everyone) enjoy learning about the behind the scenes "magic" that goes into these libraries. I agree, you shouldn't teach beginners bad habits, but they should also know where you're able to use var/let and what the differences are. Imagine you're working for a client who demands vanilla JS or a specific browser compatibility, etc.

Thread Thread
 
artemtam profile image
Artem Tamoian

Usually there is no need for even axios, because fetch is enough for most of the use cases. And there is Babel for compatibility.

Thread Thread
 
artemtam profile image
Artem Tamoian

Okay, my point is that you clearly don't have a lot of experience in JavaScript and software engineering. This is totally okay, but if you're not confident in what you're doing, please, don't write articles trying to teach people – you mislead them.

Your content, in general, is not high-quality, most of your articles are basically retelling the docs. And usually retelling inaccurately, this is the problem. You don't make any value to anyone.

It's up to you for sure, though I suggest you finish your bachelor's, work full-time for a few years and get back to blogging with experience and understanding.

Thread Thread
 
acroynon profile image
Adam Roynon

I appreciate the feedback but it is very presumptuous and condescending, thanks

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

As I will almost always wrap in new Promise anyway, I would suggest axios, which is XMLHttpRequest based and Promise based.

Of course, fetch is already a Promise.

Collapse
 
acroynon profile image
Adam Roynon

Yes I agree, axios is a brilliant little library to handlr async requests