AJAX

AJAX revolutionized the web and brought about the trend toward modern web development and single page web applications. AJAX allows you to write JavaScript code that can fetch data from a server on the web and display it in the browser without requiring a full page reload. In other words, you can make HTTP requests with your JavaScript code.

AJAX stands for asynchronous JavaScript and XML. 'Asynchronous' means that you can make these HTTP requests in the background, and it won't block your web page while the requests are in progress. You can check out this article for an overview of asynchronous JavaScript.

The 'XML' in AJAX is now obsolete, but in the old days it was assumed that the data you fetch would come to you as XML code, but nowadays JSON is the standard encoding.

You can use the fetch() function in JavaScript to make an 'AJAX call' (aka an HTTP request). The fetch() function returns a Promise object, so you need to understand how to use functions that return promises (for more on that, you can check out this article on using promises).

To get started with this activity, create a page named ajax.html and put this starter code into it:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AJAX</title>
  <script>
  window.addEventListener("load", () => {
    
    const btn = document.querySelector("[name=btn]");
    const div = document.querySelector("#container");

    btn.addEventListener("click", () => {
      
      const getAllPosts = async () => {
        alert("TODO: make AJAX call to get all blog posts");
      }

      getAllPosts();
    
    })

  });
  </script>
</head>
<body>
  <input type="button" value="AJAX Call (HTTP Request)" name="btn">
  <div id="container"></div>  
</body>
</html>

Note that the getAllPosts() function is declared as async. This is because in the next step we'll add code to it that calls the fetch() function, which returns a Promise object. When we call fetch() we'll use the await keyword.

We need a web service to make our AJAX call to. For now you can think of a 'web service' as a site that responds to requests by sending raw data, rather than traditional web pages. We'll use a web service called 'JSONPlaceholder', which is a web service that was created to give developers something to practice with (perfect for us!).

Visit this URL in your browser:

https://jsonplaceholder.typicode.com/posts/

When the page loads, you'll see that the response is raw data that simulates a collection of blog posts.

To get the data for just one blog post, enter this URL:

https://jsonplaceholder.typicode.com/posts/1

Note that the URL above ends with the number 1, which is the id of the post we want to 'GET'.

Look at the response that you get when you make this request in the browser, and note that it is a JSON string. We'll have to parse this string into an object. The object, will have the following properties: userId, id, title, body.

Now let's go ahead and make our first AJAX call. Replace the alert("TODO: make AJAX call to get all blog posts"); in the starter code with this:

const url = "https://jsonplaceholder.typicode.com/posts/";
const response = await fetch(url);
console.log(response);

Reload the page, and then press the button to initiate the AJAX call. You should see in the console log that the response is an object that represents the HTTP response from the web service. Note that this object has a status property (which should be 200), and it has a body property which contains the data that we requested.

The response object has a json() method that we can call to get the body. This method returns a Promise object (I'm not sure why), so we'll need to use the await keyword when we call it.

Add this code, just under the console log:

const body = await response.json();
console.log(body);

Reload the page and press the button, you should see that the body of the response (which was sent to us as a JSON string) has been parsed into an array of objects (each object in the array represents a blog post).

A single page web application usually makes AJAX calls like the one we just did, and then display the data by manipulating the DOM.

So, now add this code, just after the last console log:

const ul = document.createElement("ul");

body.forEach(post => {
  const li = document.createElement("li");
  li.innerHTML = post.title;
  ul.append(li);
})

div.append(ul);

Reload the page and then click the button. You should see a list of blog post titles appear.