Week 4: Single-Page Applications with AJAX


This week, I’ve decided to take a break from Java. Today I want to introduce to you one of the sub-concentrations of Zip Code Wilmington: Single-Page Applications with AJAX.

What you will be learning today is a simple but powerful abstraction called Single-Page Applications (SPA). In addition, you will have the opportunity to implement this concept using one of the most popular methods of invocation, Asynchronous Javascript and XML (AJAX). SPAs are relatively new to the web development scene. Almost all your favorite websites implement such a technique.

So what is a Single Page Application exactly?

Well the blunt answer is it’s all in the name. There is no deep meaning to it. Single Page Applications are applications built to run on a single webpage. If you want to go a little further into it, we can briefly talk about the end goal of implementing such a concept: to provide the user with a very smooth user experience.

Whenever you visit a website, you’re sending a message to a server somewhere. That server does a lot of processing and finally sends HTML back to your browser. Think about any website for a second. It’s usually the case that the site has a general look and feel across a majority, if not all, of it’s webpages. Now prior to SPAs, clicking a link on a webpage would require the server to send all the HTML content with some changes back.

As developers, we want to minimize the amount of workload as much as possible, whenever possible, because the more information a computer has to work with, the longer it will take to finish said work. If a website has a general look and feel across all its webpages, we can load the general template once and then load different content into the template based on the user's needs. On small-scale web applications, the difference might not be noticeable, but imagine a large-scale web application such as Twitter or Wolfram Alpha that works with vast amounts of data. These applications provide fluid user experiences through the use of SPAs.

Now that you understand SPAs, let’s get to creating a simple Single-Page Application using Asynchronous Javascript.

Creating a simple Single-Page Application

We’re going to create an application that just reads data from a data file and loads the data into our HTML. But if you remember, what makes this application special is the fact that the data will be loaded  after our HTML loads. We can choose to load our data whenever we want - when a user clicks a button, after a certain time, when something in our HTML changes, it’s up to you! I will choose to load our data when the user click a button.
Here is our tiny HTML page with our script:


<!DOCTYPE html>
<link href=“style.css” rel=“stylesheet” />

<div><h2 id=“user">User’s name goes here</h2></div>

<button type="button" onclick=“loadUser()”>Load User</button>

function loadUser() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", “http://example.com/user/user_info.txt", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(“user").innerHTML = xhttp.responseText;


If you’ve never seen HTML (although I bet you have and just don’t remember), it’s a very simple markup language.

The first line, <!DOCTYPE html> tells your browser this is an html file. Then we begin an html tag with <html> and close it with </html>. This is the general syntax of an HTML tag: <tag>[content goes here]</tag>. Notice everything goes inside <html></html>. Some tags don’t need closing tags: <img src=“photo.jpg” /> because nothing goes in between them.

The <head> tag holds information about our webpage such as our stylesheet (this is what makes webpages look pretty and interesting). We will not be working with stylesheets in this post. Information in the head tag is only for the browser and developers to work with behind the scenes. Noting in between them is printed to screen. Only information in the <body> tag get printed to screen.

The first element in our <body> is a <div>. This is a division element. They help you group things together. Chances are any webpage you visit is rife with <div> tags or some of the many other division elements.

Inside our <div> is an <h2> tag. This is one of the six header tags available (h1, h2, h3,…). These will display the user’s name with big and bold lettering (by default h1 is the largest, then h2,…). I’ve given our <h2> an id of “user”. This is like any  ID card you possess. There is only one of you so there can only be one person with your ID. Likewise, there can only be one element in our HTML page with that id. This will be used to reference the <h2> in our script.

The  <button> element will render as simply a button. Our button has an attribute, onclick, whose value, "loadUser()", corresponds to a function we created in the <script> tag.

The <script> tag holds code that either manipulates data in our HTML our retrieves information from an outside source. Our script does both.

Here’s what our data from http://example.com/user/ user_info.txt looks like:
James Bond


Now let’s break down our script:

  1. function loadUser() - First we define a function called loadUser. Remember our button calls this function when it is clicked.
  2. var xhttp = new XMLHttpRequest() - Here we create a new instance of XMLHttpRequest which provides a way to retrieve data from a URL without having to refresh the whole page and we begin with
  3. xhttp.open("GET", “http://example.com/user/user_info.txt", true) - This says start a GET request (hey browser get this for me) which will retrieve user_info.txt from the specified URL and set asynchrony to true. Setting this to true will allow our script to do other things while waiting for the file to be loaded. This is a very important aspect of Single-Page Application programming. You don’t want to hang your application for what could be a long time (for a big file or slow server for example).
  4. XMLHttpRequest goes through states when it is working. We want to do something when it is in the finished or DONE state. We do this by setting xhttp.onreadystatechange to an anonymous function (a function with no name).
  5. if (xhttp.readyState == 4 && xhttp.status == 200) - In the function we check if the state of the request is one that of the DONE state. The DONE state is represented in Javascript by the number 4. We also make sure the status of the request is a successful one. There are many codes that represent different outcomes of a request’s adventure to and from a server - 200 signifies success.
  6. document.getElementById(“user").innerHTML = xhttp.responseText - document represents our HTML document. We use a method in Javascript, getElementById(“user”), to reference our <h2> which, if you remember has an id of “user”. We then access the inner content of the <h2> with innerHTML. With this, we can set the inner content to whatever we want. In our case, we want to set it to the information retrieved by the XMLHttpRequest instance. That information is stored in xhttp.responseText.
  7. Finally, we send the request with xhttp.send() and the magic begins.

When the user hits the button, our script’s function, loadUser(), will execute and the contents of our <h2> element will change to read “James Bond”.

Here’s a task for you: Try reading more than one line into multiple tags.

Have fun and see you next week!

[content_band inner_container="true" padding_top="10px" padding_bottom="10px" border="none" bg_pattern="http://www.zipcodewilmington.com/wp-content/uploads/Triangles__1441830476_50.73.209.90-compressor.jpg"]

Want to learn more about AJAX? Check out more about our curriculum and apply today!


AJAX coding CSS HTML round-up Single Page Applications tutorial