From the Console to the Page:

So we now have our function that logs the API in a JSON format to the console.

But how does this look if we try to insert it onto the page?

If we add the following line of code to the printDataToConsole(data) function, we can see:

Click To See Result


The code is returning to the page the typeof() rather than the result - the inner details of the Object.

So where do we go from here?

Firstly, note that in the API there are many, many different Objects: People, Planets, etc.

So we need to be able to retrieve these details and not just the global Object. So let's rewrite the code a little first.

We are going to replace the printDataToConsole(data) with a more aptly named one, that being writeToDocument() and then align the rest of the code with this function:

Step by step process:

1: Replace printDataToConsole(data) with writeToDocument(type) function. This tells the function to return the type (the film, the people, the planet etc from the API) to the page

2: Call the getData() function and tell it to insert the type from the API onto the page as its first argument. Argument 2 is an anonymous function that calls for the data within the type from the API - Luke Skywalker, for example.

3: Insert the data from within the type from the API into the element <div id="dataDiv"></div> (that we shall create after this explanation).

4: Modify the getData() to include the type from the API.

5a: Remove the API URL from the xhr.open() function.

5b: Create const baseURL and assign it the "string" value of the base URL of the API.

5c: Rewrite xhr.open() to call baseURL and its type. Thus, when called, it will call https://ci-swapi.herokuapp.com/people/ or /planets/ etc.

The code fully rewritten:


Now, we need to write some HTML to reflect these changes. We need 6 <button>s, one for each ot the type "strings" in the API. These buttons call the writeToDocument(type) function: