Skip to content

Prep 11: Saving and Sharing

This week, we’ll be learning about a different way to persist data. Instead of localStorage, we’ll be using the URL and files to save and share data.

Textbook Reading

Preplabtivity: Meals on Wheels

We’ve made a small meal tracker! You pick a meal for breakfast, lunch, and dinner, and it charts your calories.

Meal Tracker app screenshot

But now, when you reload the page, your meals are gone. We’d also love to be able to share our meals with others, like your friends (idk why you’d want this) or your nutritionist (more likely).

You’ll fix that in three ways:

  1. Query string: put the data in the URL so you can share it with a friend
    • This means that, when the page loads, you’ll need to first CHECK the URL for data and fill in the form if it’s there.
    • We’ve never really done a “page load” in detail, so pay attention to the DOMContentLoaded event!
  2. Download: save the meals as a JSON file
  3. Upload: load a JSON file back into the form
    • This requires us to use a file input and the File API to read the file.
    • We’ll use JSON.parse() to turn the string back into an object, then fill in the form and draw the chart.

We’ll start this activity together in class, and you’ll finish it on your own.

Getting Started

You’ll start from a working meal tracker and add the save and share features to it.

  1. Download the starter code here: meals.html
  2. Open it in VS Code and run it with Live Server.
  3. Test it out: Pick some meals and click Calculate Calories.
    • Notice that picking a meal fills in its calories, and you can change the number.
    • The calculate calories button draws a chart, like last week.
  4. Read through the <script>. Two functions will be useful later:
    • drawChart(breakfastCalories, lunchCalories, dinnerCalories) redraws the chart with the three calorie numbers you pass it. Look at how the submit handler calls it.
    • getMeals() returns the form’s data as an object.
      • Try it in the DevTools console (F12): pick some meals on the page, then type getMeals() into the console and hit enter.

Step 1: Let the form make a query string

A query string is the part of a URL after the ?. It holds key=value pairs separated by &. You’ve used one before to send data to an API, like ?limit=20.

Forms typically make query strings on their own. Our form’s submit handler calls e.preventDefault(), which stops the form from doing its normal job.

  1. Delete the e.preventDefault() line.
  2. Pick some meals and click Calculate Calories again.

    Check it

    The page should have reloaded. Now, take a look at the address bar.

    You should see something like:

    meals.html?breakfast=eggs&breakfastCalories=400&lunch=salad&lunchCalories=500&dinner=&dinnerCalories=
    

    Each key is a form field’s name, and each value is what was in that field. This is what a form normally does when submitted: it loads the page again with its data in the URL.

    This is essentially a bunch of key-value pairs again:

    Key Value
    breakfast eggs
    breakfastCalories 400
    lunch salad
    lunchCalories 500
    dinner
    dinnerCalories
  3. But the form is empty now and the chart is gone! That’s because the browser has reloaded the page.

    • So while the data is in the URL, there’s no code that reads it and populates the form and the chart.
    • We need to rewrite this so that it’s no longer the submit button that draws the chart, but the page load event. The submit button will just update the URL.
    • Thus take a note of the drawChart() call, and then move on to the next step.
  4. Delete the whole submit event listener block (under the // Step 1 comment).

    • The form doesn’t need any JavaScript to submit. You’ll draw the chart on page load in Step 2.

Step 2: Read the query string

When the page loads, your code needs to read the query string and put its values back in the form, plus render the chart.

  1. Write fillForm(meals).

    • It takes an object like the one getMeals() returns, and sets each of the six form fields to its value.

      Example:

      fillForm({
          breakfast: "eggs",
          breakfastCalories: "400",
          lunch: "salad",
          lunchCalories: "500",
          dinner: "",
          dinnerCalories: ""
      });
      
  2. Under the // Step 2 comment, write an event listener for the DOMContentLoaded event yourself.

    • Your code needs to run when the page loads. The browser fires a DOMContentLoaded event on the document once it has read all of the page’s HTML.
    • It works just like the click and submit listeners you’ve written before, except that it goes on document.

    Check it

    Put a console.log("page loaded") in your listener and reload the page. You should see the message in the DevTools console once each time the page loads.

  3. Inside your listener, read the query string into a URLSearchParams object, and store it in a variable named params. You’ll need to look up two things:

    • Where is the query string? The browser keeps the current URL in window.location. Find the property that holds just the part starting at the ?.
    • How do you make a URLSearchParams? Check the constructor on the URLSearchParams page. What can you pass it?

      Hint

      You can pass it a string, but it has to be the part starting with ?. If you pass it the whole URL, it won’t work.

      Hint 2

      Try window.location.search!

    Check it

    Add console.log(params.get("breakfast")) and reload a page that has a query string. You should see the breakfast you picked, like eggs.

    You can manually change the URL and add a query string too, like ?breakfast=toast&breakfastCalories=200&lunch=soup&lunchCalories=300&dinner=pasta&dinnerCalories=600. Reload the page and check the console again.

  4. If params.size is more than 0:

    • Turn it into an object that has the format that fillForm expects. There should be a few built-in methods to do this, or you could do it manually.

      Hint

      params has a method called entries() that returns an array of [key, value] pairs.

      Hint 2

      Object.fromEntries() can turn an array of [key, value] pairs into an object.

    • Pass that object to fillForm.

    • Call drawChart(...) with the three calorie values. Get each one from the object you just made.

    Check it

    Submit the form. The page reloads, but your meals stay in the form and the chart is drawn. Now copy the URL and open it in a different tab. Your meals should be there too!

Step 3: Download a JSON file

A URL is good for a little data. For more data, or to keep a backup, a file is better.

Downloading the form’s data as a JSON file takes four parts:

  • Turn the data into a JSON string with JSON.stringify().
  • Wrap the string in a Blob, which is a chunk of file data in memory.
  • Get a temporary URL that points to the Blob with URL.createObjectURL().
  • Make a link to that URL with a download attribute, and click it from JavaScript.

Phew! That’s a lot of steps, but it’s not too bad once you see it in action.

  1. Read James Milner’s Downloading Text, JSON and Images with Client-Side JavaScript.

    Typo in the article

    The article’s examples make a variable named anchorEl, but then call anchor.click(). If you type it exactly, you’ll get ReferenceError: anchor is not defined. Use anchorEl.click() instead.

  2. Follow its JSON example to write the download button’s click handler.

    • Use getMeals() as the data and name the file meals.json.
    • Type the code line by line instead of copying and pasting it. Typing it makes you read each line, and you’ll need to know this for the future.

    Make the file readable

    JSON.stringify(data) puts everything on one line. Try JSON.stringify(data, null, 2) instead: it adds line breaks and two-space indents.

    AI Time: Explain Code You Wrote ✨

    Typing code from a tutorial doesn’t mean you understand it. Paste your download handler into an AI chat (see AI Tools) and ask:

    “I’m learning vanilla JavaScript. Explain what each line of this code does, and what would happen if I left out the .click() line or the URL.revokeObjectURL() line.”

    Then verify one claim it makes: try removing a line, or look the function up on MDN. Was the AI right?

  3. Pick some meals and click Download JSON.

    Check it

    Open meals.json in VS Code. It should look like:

    {
      "breakfast": "eggs",
      "breakfastCalories": "400",
      ...
    }
    

Step 4: Upload a JSON file

Now go the other way: read a file the user picks and fill in the form.

The file input’s files property is a list of the files the user chose. The starter code already checks that there’s at least one. Finish the upload handler:

  1. Get the first file: fileInput.files[0].
  2. Read its contents as text with await file.text().

    • Reading a file takes time, so like fetch, it returns a promise.

    Async Operations

    Don’t forget! You can only use await inside an async function. Where is the async keyword declared for this function?

    Dont’ worry about FileReader

    The article you read mentions FileReader, which is an older way to read files. The newer file.text() is simpler and works just as well.

  3. Turn the text into an object with JSON.parse().

  4. Call fillForm with the object, then call drawChart(...) with the three calorie values from that object.

    Check it

    Reload the page so the form is empty. Choose the meals.json you downloaded and click Upload JSON. Your meals should come back and the chart should be drawn.

    Then open meals.json in VS Code, change a number, save it, and upload it again. The chart should show your change.

  5. Test your upload with files your app didn’t make.

    AI Time: Generate Test Data ✨

    (This is my favorite AI use-case btw!)

    Your upload code works on the file your app made. But users can upload anything. AI is great at making test data quickly. Paste one of your meals.json files into your AI chat and ask:

    “Here is a JSON file my web app imports. First, make one valid file with the same keys but different meals and calories. Then make five test files that could break my import code, like invalid JSON, a missing key, an extra key, a meal that doesn’t exist, or a negative number. Explain what each one tests.”

    Save each one as a .json file and upload it. Start with the valid file: the form and chart should change to its values. Then try the others. Which ones does your code handle? Which ones break it?

Challenges

If you finish early, try these:

  1. Bad files: What happens if you upload a file that isn’t JSON (try a .txt file renamed to .json)? Use try/catch around JSON.parse to show a helpful alert instead.
  2. Keep the URL in sync: After an upload, the URL still shows the old meals. Update it without reloading the page with history.replaceState():

    history.replaceState(null, "", "?" + new URLSearchParams(meals));
    
  3. Remember the day: Save the meals to localStorage whenever the form is submitted, and load them when the page loads if the URL doesn’t have any.

Submission

Submit your completed meals.html file to Gradescope. You can submit as many times as you like.

Other Resources