Dynamic websites

This chapter is a short introduction to XMLHttpRequest, also called Ajax requests. Such requests lets you dynamically change the content of your page, not solely relying on having to load the entire page again.

The moment you click a link on a web page your browser immediately fires of an HTTP request. While its waiting for the HTML from the server you might be presented with a blank screen. Nowadays, this blank screen is only visible for a couple of milliseconds.

Ajax

However, not all websites require the user to load the entire page when a link is clicked. In fact, you could argue that the most popular websites today are loaded dynamically with XMLHttpRequests. This means that the content you see in your browser is loaded after the initial payload. You have probably noticed this behaviour while scrolling down your Facebook feed, or clicked on an e-mail in Gmail, where the content is loaded when you need it.

Example

XMLHttpRequest is an API that enables JavaScript to send `HTTP` requests. Here is an example of how a web page would load a "newsfeed":

const request = new XMLHttpRequest();

request.open('GET', '/newsfeed', true);

request.onload = function() {
    if (request.status === 200) {
        console.log\(request.responseText\);
    } else {
        console.log\(request.status\)
    }
};

request.send();

On the first line we instantiate a new XMLHttpRequest and assign it to the constant request. We proceed by instructing the request to use the HTTPmethod GET to fetch from the service's `/newsfeed` path. The last argument is a flag that determines if the request should be handled asynchronously or not. If this flag is set to true, as it is in this case, a notification of a completed transaction is provided using event listeners. If it is false, the send() function does not return until the response is received.

The onload function is only executed when the server has responded to the request. In the example above we log the response text to the console, but we could have manipulated the document to update the page dynamically, e.g. updating an element's innerHTML property.

The else block will log the request's status to the console. This could be replaced with if else` statements, handling different status codes.

Finally we fire the request by calling send() on it. But what is it we're receiving from the server? More on that in the next section.

As this course only concern itself with the client side, we won't use the HTTP method POST. But you should know about GET, POST, PUT and DELETE.

  • GET

    Used to get data from a service (server), without changing the state of the data.

  • POST

    Used to post data to the service, i.e. storing new data in a database.

  • PUT

    Used to update data, i.e. updating a user's profile in a database.

  • DELETE

    Used to delete data, i.e. delete a user from the database.

Request properties

When you receive a response from the server, you need to access the data somehow. In the the example the content, once received, is stored in the constant request. Here you see that we check if the `request.status` is equal to 200. status is one property, containing the HTTP response code. responseText is the property containing the actual data that the server returned. The responseText is a string that you can do something with. If the string contains JSON, you can use JSON.parse(string) to parse the string into a JavaScript object.

You can see all the properties at MDN.

HTTP responses

When you're requesting data from a server over HTTP there are some response codes defined with the HTTP standard. These codes says something about what happened. The codes are sent from the server to the client.

In the previous example, where the `if` statement checks if `request.status == 200`, i.e. the response was successful, the successful response is handled. The request.status could be another code. The most important are:

  • 200 OK

    The request was successful.

  • 400 Bad request

    This response means that the server could not understand the request due to invalid syntax.

  • 401 Unauthorized

    Authentication is needed to get requested response. This is similar to 403, but in this case authentication is possible.

  • 403 Forbidden

    The client does not have access rights to the content, so the server is rejecting to give a proper response.

  • 404 Not found

    The server could not find the requested resource.

  • 500 Internal Server Error

    This means that the server has encountered a situation it doesn't know how to handle.

  • 502 Bad Gateway

    This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.

  • 503 Service Unavailable

    The server is not ready to handle the request. This could mean that the server is down or overloaded.

You can see all the HTTP codes and their definition at Mozilla Developer Network.

JSONP

Up until now we have only been concerned with loading content dynamically from the same server as the initial page load. However, sometimes you will want to load content from a completely different server. An example could be loading cute pictures of cats from Flickr on your blog.

Unfortunately for you, there's a restriction called Same-origin policy in the web development world. Due to security reasons, a page on one server can not simply load content of another. This means that your blog on "cute-kittens.wordpress.com" can not load content with an XMLHttpRequest from flickr.com.

To circumvent this restriction you can use a technique called JSONP. In short, JSONP exploits the lack of Same-origin policy when loading JavaScript from one server of another. This technique requires however that the other server provides a so called callback parameter.

Last updated