Chapter 8 - Requests and Servers

So we just invoked our makeRequest function in the previous chapter. It looked like this:

makeRequest(url, callback);

The third point/comment in our application was this:

  1. Declare a function that is responsible for making HTTP requests.

and this was its declaration:

function makeRequest(url, callback) {
  var xhrObject = new XMLHttpRequest();
  xhrObject.onload = function () {
    var parsedResponse = JSON.parse(xhrObject.responseText)
    callback(parsedResponse);
  };
  xhrObject.open('GET', url, true);
  xhrObject.send();
}

In the interwebs we can make requests to servers and get their responses. Seems vague? Well, servers are just computers. Like the computer you're using right now. Only they don't have screens attached to them (most times), and they are configured to serve a large load of requests. So they're basically just strong computers. Simple enough?

Requests are when one computer is sending data requesting certain, other data from another computer over the network. Responses are when the computer that has received the request sends the requested data as a response to the initial request.

When you navigate your browser to http://pornhub.com your computer first resolves the URL to an IP address. IP address, simply put, is the address of a computer on the network and is how it can be reached by other computers on the network. Once your computer has Pornhub's underlying IP address, it sends the request to its server. Pornhub's server receives your computer's request and prepares the data (your porn videos) for you. Lastly, Pornhub's server responds to your computer's request and sends all your porn back to your computer which can be found with your IP address which is part of your computer's request.

So that's what our makeRequest function is intended to do. It's designed to make a request to the specified URL (passed as the first argument to it), and then, when it receives the response to its request from the server, it does something else. That something else is an invocation of yet another function. That function is the second argument we passed to it. That function that's to be called at a later time is referred to as a callback function and is supposed to handle the weather data it will receive eventually.

We've made some serious progress but now our brains hurt. Still don't get what a callback function is? I didn't get it for the longest. We'll discuss it more later. In the meantime let's take a little break and talk some fluff.

Table of Contents
Home