CSE 154

Week 6 Section: Using JSON with JavaScript and AJAX

Today's Agenda

Review AJAX with fetch and JSON

Practice using JSON as a data format to process with JS

Build a cool Trivia webpage!

Recall: JavaScript Objects and JSON

JSON is a way of saving or storing javascript objects (the technical term is "serializing" which is just a fancy word for turning an object into a savable string of characters)

Browser JSON methods:

Today: Building a Trivia game with AJAX and JSON!

We'll build this

Start with this index.html and starter.js (there is no CSS).

Exercise 1: Fetch Trivia

Step 1: Determine the url we want to fetch from:

CSE 154 Trivia web service url:

  • https://courses.cs.washington.edu/courses/cse154/webservices/trivia/trivia.php

Step 2: Determine what questions we can ask:

  • Parameters: mode=all (required)

JSON Response Format

The Trivia Web Service's HTTP response will look like this:

{
  "trivia": [
    {
     "question": "What's a cat?",
     "answer": "An animal!",
     "difficulty": 3
    },
    {
      "question": "What's a dog?",
      "answer": "An even better animal!",
      "difficulty": 1
    },
    ...
  ]
}

JSON

Fetchin'

Knowing the URL and parameters, how can we use fetch to get the JSON response containing trivia?

https://courses.cs.washington.edu/courses/cse154/webservices/trivia/trivia.php?mode=all

Debugging Tips for your First Fetch Calls

Fetch the JSON and log it in your response function, then set a breakpoint in your browser tools to see if you have the correct parameter format in the function.

Also check the Network tab to see the response!

Exercise 2: Add Questions

Fill the #q-output paragraph with a random question from the JSON result when "New Question" is pressed.

Expected output for ex2

Note that the buttons on the page are initially disabled. You should enable them when the JSON data from Exercise 1 is successfully stored.

If there is an error when fetching the data, "catch it" and populate #q-output with a user-friendly error message of your choice.

(tips on getting random array value on slide below)

Getting a random object from an array

Choose a random element from a list like so:


/**
 * Returns an element chosen randomly from a given array.
 * @param {[*]} choices - array of elements
 * @returns {*} - a random element of choices
 */
function randomChoice(choices) {
  let index = Math.floor(Math.random() * choices.length);
  return choices[index];
}

Exercise 3: Reveal Answers

Now, let’s fill in the corresponding answer when "Show Answer" is pressed.

You may want to think about storing the just-shown question in a module-global variable. Question: Why is this an appropriate choice for a module-global variable?

After the "Show Answer" button is pressed, it should be disabled until a new question is chosen (in which case it should be re-enabled). See the slide below for an example output.

Exercise 3: Expected Output

Expected output for Exercise 3 Before clicking Show Answer

Expected output for Exercise 3 After clicking Show Answer

Exercise 4: Indicate Difficulty

What's trivia without some difficulty to measure against? In this part, we'll use the difficulty provided in the JSON data to add more information for each question.

Note that in the JSON data, there is a difficulty attribute for each item: a difficulty value of 1 corresponds to Easy, 2 to Medium, and 3 to Hard.

Exercise 4 Example Output Example output

Exercise 5: Extending to a Public API

Let's try out our first public API!

There is a trivia API you may use at opentdb.com.

Update your solution from the earlier slides to use this API instead of the one we gave you, and replace the "trivia" JSON attribute with "results" and "answer" to "correct_answer".

  • This API uses almost the same syntax for a JSON response as you just used for our 7-question JSON, but has much more additional questions and information in the JSON. For example, the url https://opentdb.com/api.php?amount=50 will return 50 random trivia questions with information about the question type, category, etc.

Tips for JSON Formatting (when using new APIs)

When looking over the response JSON, it will be pretty messy since there is so much information and the API doesn't format the JSON output as we do. We recommend using this JSON Viewer Chrome Extension for easily viewing the JSON structure in your browser!

You may alternatively find it useful to copy/paste the JSON with this JSON "pretty print" tool and compare with the JSON output you used in Part I.