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
- URLs MDN & Friends
- MDN: Window: location
- MDN: URLSearchParams
- Files MDN & Friends
- Modern JavaScript Tutorial: Blob
- Modern JavaScript Tutorial: File and FileReader
- Review MDN & Friends
- MDN: JSON.stringify() and JSON.parse()
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.

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:
- 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
DOMContentLoadedevent!
- Download: save the meals as a JSON file
- We’ll use
JSON.stringify()to turn the form data into a string, then make a Blob and a temporary URL to download it (it’s a weird process, but it works!).
- We’ll use
- Upload: load a JSON file back into the form
- This requires us to use a file input and the
FileAPI 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.
- This requires us to use a file input and the
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.
- Download the starter code here: meals.html
- Open it in VS Code and run it with Live Server.
- 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.
- 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.
- Try it in the DevTools console (F12): pick some meals on the page, then type
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.
- Delete the
e.preventDefault()line. -
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 -
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.
-
Delete the whole
submitevent listener block (under the// Step 1comment).- 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.
-
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: "" });
-
-
Under the
// Step 2comment, write an event listener for theDOMContentLoadedevent yourself.- Your code needs to run when the page loads. The browser fires a
DOMContentLoadedevent on thedocumentonce it has read all of the page’s HTML. - It works just like the
clickandsubmitlisteners you’ve written before, except that it goes ondocument.
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. - Your code needs to run when the page loads. The browser fires a
-
Inside your listener, read the query string into a
URLSearchParamsobject, and store it in a variable namedparams. 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 theURLSearchParamspage. 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, likeeggs.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. - Where is the query string? The browser keeps the current URL in
-
If
params.sizeis more than 0:-
Turn it into an object that has the format that
fillFormexpects. There should be a few built-in methods to do this, or you could do it manually.Hint
paramshas a method calledentries()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
downloadattribute, and click it from JavaScript.
Phew! That’s a lot of steps, but it’s not too bad once you see it in action.
-
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 callanchor.click(). If you type it exactly, you’ll getReferenceError: anchor is not defined. UseanchorEl.click()instead. -
Follow its JSON example to write the download button’s click handler.
- Use
getMeals()as the data and name the filemeals.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. TryJSON.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 theURL.revokeObjectURL()line.”Then verify one claim it makes: try removing a line, or look the function up on MDN. Was the AI right?
- Use
-
Pick some meals and click Download JSON.
Check it
Open
meals.jsonin 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:
- Get the first file:
fileInput.files[0]. -
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
awaitinside anasyncfunction. Where is theasynckeyword declared for this function?Dont’ worry about FileReader
The article you read mentions
FileReader, which is an older way to read files. The newerfile.text()is simpler and works just as well. - Reading a file takes time, so like
-
Turn the text into an object with
JSON.parse(). -
Call
fillFormwith the object, then calldrawChart(...)with the three calorie values from that object.Check it
Reload the page so the form is empty. Choose the
meals.jsonyou downloaded and click Upload JSON. Your meals should come back and the chart should be drawn.Then open
meals.jsonin VS Code, change a number, save it, and upload it again. The chart should show your change. -
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.jsonfiles 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
.jsonfile 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:
- Bad files: What happens if you upload a file that isn’t JSON (try a
.txtfile renamed to.json)? Usetry/catcharoundJSON.parseto show a helpfulalertinstead. -
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)); -
Remember the day: Save the meals to
localStoragewhenever 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
- Go Make Things: How to upload and process a JSON file with vanilla JS (uses
FileReaderinstead offile.text()) - MDN: Blob
- MDN: URL.createObjectURL()
- MDN: File: text()
- MDN: Sending form data