With AJAX, we can build Single Page Applications (SPA) that render dynamically with user input. Personally, I can’t remember the last time I used a webpage that required full reloading of the page any time I wanted to interact with it. Asynchronous programming allows us to interact more fluidly with our digital environment.
When we talk about AJAX and asynchronous code, we’re usually referring specifically to client-server communication. AJAX helps us write code that allows our app to communicate with a server without interrupting the user’s interaction with our client side, and then potentially update our client interface with any data changes that the server sends back in its response.
So, how does this happen? Enter the
The XHR object is an object found on modern browsers that has a bunch of really useful properties that allow us to interact with server asynchronously.
We can use this XHR object and its methods to, among other things: (1) send requests from our client to the server, (2) check the state of a request, (3) receive a response from the server, and potentially (4) execute some action, depending on the success or failure of a server response.
From the image above, you can see it’s got all these neat properties, including some it inherits from its
The ones we're going to focus on first are
.send() (which live on the proto). When making an AJAX request with an XHR the fundamental steps are to (1) instantiate the XHR object, (2) open the request, and (3) send the request.
Let's dissect this. On line 2, we instantiate the object (pseudoclassically!) with the new keyword. On line 3, we call
.open(). Our first parameter there indicates the
method (i.e. GET or POST). The second,
url, is where we're sending our request. The third parameter is a boolean which tells our code whether or not to run this asynchronously, so we've set ours to
Then we use
.send() to send off the request!
Line 5 is where the magic happens.
.onload() is one of a couple methods on the XHR object that help us implement the asynchronous nature of our call. We can optionally pass in two callback functions, one of which will run in case of response success, the other in case of failure.
In this case, we're only running the success callback if our
status code comes back between 200 and 300, which means the request was successful.
And then we can just call our AJAX function like we do in the image above, passing in the method, the url, and whatever callbacks we want.
Hopefully this post took some of the mystery out of AJAX and the XMLHttpRequest object. AJAX queries are vital to modern programming and important to learn how to implement. The XHR object is just one of several ways to make an AJAX call to a server.