This site uses third-party cookies, learn more or accept
dark light

The Better Version of an XMLHttpRequest

Written by Max Pelic, updated on

I've been working on writing some client-side JavaScript recently, including my recent Password Strength Checker, and in the process of making these programs, I have discovered some new JavaScript functions that makes the development process much easier and simpler.

Asynchronous Functions

Before we jump into the fetch function, let's quickly cover how asynchronous functions work. The beauty of asynchronous functions is they can be called using two different methods: using promises, and using the await keyword.

First, let's take a look at how an asynchronous function looks:

1async function myAsyncFunction(){

2 ...
3 return something;
4}

Unlike normal JavaScript functions, an asynchronous function can wait for other resources (like an ajax request). When calling an asynchronous function, you can wait for the result by treating it like a promise, or, if you're calling it from another asynchronous function, using the await keyword. Let's take a look at how each of these would work:

1//treat the function like a promise

2
myAsyncFunction().then(response=>{
3 //do something
4
}).catch(error=>{
5 //do something else
6
});
7
8//using the await keyword
9
let result = await myAsyncFunction();

Personally, whenever possible, I like to use the await method, since the code that uses the result can be in the same block (instead of the .then function).

Fetch instead of XMLHttpRequest

As someone who avoids libraries at all costs, I used to use XMLHttpRequests for every ajax request I would make. However, those requests can get kind of tedious to write. If you're making a POST request, make sure you include the multipart/form-data header, or the data won't go through. Make sure you're checking the state of the request in the listener, or you might be trying to handle the data before it's ready.

Instead of using the XMLHttpRequest object, I started using the fetch function. the fetch API is an asynchronous function that makes the request and returns the response data. You can also manipulate headers, form data, and anything else you might need to deal with right in the function. Here's an example of how the fetch function works:

1let requestObject = await fetch('https://example.com');

2let jsonData = await request.json();

And just like that, with two simple lines of code, you can get a JSON object from a site. You can also use request.text() to get the text content.

So there you go, ditch the XMLHttpRequest, and write some vanilla code that can easily get a response from a web page. Happy coding!

Share this article:

Previous Article: Your Password Are Weak - Make Them Better With JavaScript