For this set of exercises, use JsFiddle. You can write pure Javascript in the lower-left corner and HTML in the upper-left corner.
Today, we are going to take what we have seen with Javascript and make our Javascript tool kit even more powerful by introducing the asynchronous capabilities of JavaScript. When a computer program is asynchronous, that means that it is functioning in such a way that the program doesn't block other running programs from completing. A great example of this behavior occurs when retrieving data from the Internet. Instead of pausing the execution of all other programs, we can write code in such a way that makes a request for some data via HTTP, and allows us to continue living our lives while we wait for that data to be returned to us.
To make all of this clearer, let's take a brief tour into computer networking. To begin, computer servers are simply computers themselves which are used to provide services, data or resources to other computers (clients). In general, computers on a network are modeled in client-server relationships. This means that one computer "serves" information to a "client" (or a "customer", to use the server metaphor in a restaurant), and the client computer receives responses from the server. This pattern of communication dominates the entire internet (and Internet).
When a client sends a request, that request contains some information:
When a request comes from the browser in the form of a GET for a resource like an HTML or CSS file, the browser will render the web page using those resources. Additionally, the response will include a code, such as:
Additionally, a server can send a cookie in response to a browser. A has unique information pertaining to a user, or a session, or anything else that might help make the user's experience better. The browser will store the cookie, and later, if the browser sends a request to that domain again, it will attach the stored cookie.
On the backend server, the process includes these steps:
Today, we will be using Javascript to make requests for data using HTTP! To get started, here is a code snippet of HTML that you will use to begin this lab. We will be adding code to this snippet by following the steps one at a time.
<!DOCTYPE html> <html> </html>
<head>
element to your HTML. Within the HTML head,
add a <title>
element and include this text within the title: Async Javascript Example.<body>
element to your HTML.<h1>
element and include this text in the heading: Async Javascript Example.<button>
element within the body. Give this button an "id" field and call the id, "fetch-button". Within the button text itself,
call the button "Fetch Button".
<div>
, tag. Give this tag an id as well, and call that id "output".<script>
tag. We are going to add some Javascript!document
, and then get an element by its id (look it up if you
don't happen to remember how to do this! hint: getElementById
) to get our "fetch-button" that we made earlier. Then, add an event listener so that
when the fetch-button is clicked, a new function called "fetchData" is invoked (to do all of this, you may need to refresh on
getElementById and addEventListener).
fetch
. Fetch is an API interface which allows us to
perform HTTP requests. So, we are going to make an HTTP GET request to retrieve some data. To begin, make a call to fetch
like this (you can copy this code):
function fetchData(){ fetch(); }
'https://jsonplaceholder.typicode.com/posts/1'
. This is a "fake" endpoint with some dummy data for us to grab.function fetchData(){ fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => { // we will fill this in next }); }
if (!response.ok) { throw new Error('Network response was not ok'); } return response.json();This code handles the error in the event that there was some network problem, and if things were successful, then it returns a JSON (Javascript Object Notation) representation of the response.
.then(data => { // last piece to add, here })
.textContent = JSON.stringify(data, null, 2);In brief, this allows us to show the data we retrieved as a string.
'https://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2023/athletes/4362887'
'https://www.reddit.com/r/Wallstreetbets/top.json?limit=10&t=year'
'https://api.nasa.gov/neo/rest/v1/neo/browse?api_key=DEMO_KEY'