The XMLHttpRequest (XHR)

What is the XMLHttpRequest?

We all browse the web in a state of blissful ignorance. You don’t have to dial up anymore, you don’t have to wait for sites to load. If a site is down, you can find another site where thousands of others have already started screeching about it, so you know it’s not just you with the problem.

But regardless of whether or not you think about it, something is happening each time you open Chrome and enter an address in the search bar.

For example, maybe you want to see some cat gifs so you type imgur.com into your address bar and press enter. That is an event. Then your computer sends a request to Imgur’s server to access their homepage. The server responds, giving you access.

You go to the search bar and enter “cat gif” and hit enter. Again your browser sends a request to Imgur’s server asking for moar cats, and Imgur responds with all the cat gifs it has.

This request and response is called XMLHttpRequest, and it is the conversation that happens between your browser or computer (the client) and a website’s server every time we access the World Wide Web.

Prerequisite: Some Basic HTTP

Before we get into XHR, it’s good to have an understanding of the HTTP (Hypertext Transfer Protocol). HTTP is the protocol used for communications between clients and servers.

HTTP Request Methods

Like in life, not all conversations are the same. The different types of conversations that occur between browsers and servers are called HTTP request methods.

The most common type is the GET method, which is used for “getting,” or retrieving, information from the resource. It is the most common of all conversations, and it is also the interaction your browser had with Imgur’s server when you asked for cat gifs. You requested and they responded.

Another common one is the POST method, which is used for creating, or “posting,” new information to the resource. If you want to upload your own cat gifs to Imgur, you would create an account. Adding your information to Imgur’s server’s resource uses the POST method. The same thing happens when you add that gif of your cat knocking something into the bathtub.

PUT updates information, and DELETE deletes it. Of course you can’t just try and delete information you have no business deleting. Imgur’s servers won’t let you delete rival dog gifs because you don’t have permission to do so.

Status Codes

What if you are looking for a particular cat gif, and you find a link for it, but when you click on the link, you get an error code? Status codes indicate the status of the response the client gets from the server. The two most common are 200 and 404.

  • 200 OK If you click a link and get what you expected (or maybe not), it means the request was successful and whatever the client requested was found.
  • 404 Not Found We’ve all seen the 404 pages. It means the server couldn’t find what the client requested. That one cat gif you knew was there…actually doesn’t exist.

Using XHR With Javascript

Moar Detail IMG

Now let’s take a look at a piece of code:

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader('Content-Type', 'application/json');

//Call a function when the state changes.
xhr.onreadystatechange = function() {
    if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        console.log('cat registration successful')
    }
}
xhr.send('{"cat":{"name":"nabi","color":"tortoise shell"}}');

Yikes, I know. The first time I saw code like that, I burst into tears. Don’t worry, I don’t expect you to know what it says. I don’t even expect you to understand it after reading through it once or twice, or even ten times. If you do, that’s great! It honestly took me way longer than that, and there are still things I don’t really understand. But that’s okay. We are all learning together, and no one is going to say you’re stupid if you don’t get it. Not in this space.

So before I get into explaining parts of the code, I want you to know two things:

  • The Language is in JavaScript
  • The purpose of it is to register my cat, Nabi, to a server using XMLHttpRequest.

That it. Now let’s begin!

  1. The first thing we are going to do is create a new XMLHttpRequest object, and put it in a variable called xhr. The variable is just the name we will use to represent the request.
      var xhr = new XMLHttpRequest();
    
  2. Next comes setRequestHeader. Think of the header as information about the request being made. In this case the header is Content-Type and the value of the request body is in JSON. This means we want the request to be made in JSON.
      xhr.setRequestHeader('Content-Type', 'application/json');
    

    JSON is a syntax derived from JavaScript. What makes it useful is that it is easy for humans to read, and it is easy to parse.

  3. onreadystatchange is an event handler. I think of this as “Ready, set…!” moment before “go!” We are registering (getting ready) the function that will be called when the state changes.
      //Call a function when the state changes.
      xhr.onreadystatechange = function() {
       if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
           console.log('cat registration successful')
       }
      }
    
  4. “Go!” Here xhr sends the request to register my cat’s information in JSON as request body.
      xhr.send('{"cat":{"name":"nabi","color":"tortoise shell"}}');
    
  5. After the server processes the request and sends back the response, the state has changed and we can now call the function. This if statement reads, “if the state has completed the XHR and the status is OK, then the console log prints the response, ‘cat registration successful’”
      function() {
       if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
           console.log('cat registration successful')
       }
      }
    

To sum it up, we create a new XMLHttpRequest, set the Request Header body in JSON, then register the function that will be called after the Ready State changes. XHR sends the request and the function is called. It checks the status of the request and prints a response.

I won’t call it simple, but if you break it down into syntax you understand, it’s not so bad. I hope you have some idea of how the XMLHttpRequest works, what it’s for, and why it’s important. Everything we do on the web is made up of these requests and responses from clients to servers, asking for information and receiving it, asking to post something to the server, etc.