In this assignment, you will create a search and results page using AJAX and the Reddit API. The Reddit API endpoint you'll be working with looks like this:
GET
https://www.reddit.com/r/{subreddit}.json
To get data for the "cats" subreddit, swap {subreddit}
with "cats":
https://www.reddit.com/r/cats.json
The Search Form
At the top of the page, create a form with a single search input and a submit button. When the user submits the form, fire off an AJAX request to get all the posts for the subreddit that was typed into the search box.
Bind to the submit event on the form element instead of binding to the click event on the submit button. For example:
$("form").on("submit", function (event) {
event.preventDefault(); // prevents the form from submitting to another page
// put your AJAX code here
});
Rendering the Results
When the AJAX request responds with the data, render the title
, score
, and author
of each post. Each post can be found in data.children
. The title
should be an anchor tag that links to url
(or permalink
if you'd prefer).
Make sure that you are taking measures to protect against XSS attacks either by using DOMPurify or creating document fragments and/or nodes.
If you choose to use DOMPurify and you would like the link to open in a new tab using target="_blank"
, add DOMPurify.setConfig({ ADD_ATTR: ['target'] });
to the top of your script. Long story short, using target="_blank"
can present a security vulnerability, and DOMPurify strips out this attribute. To learn more about why, read [Target="_blank" — the most underestimated vulnerability ever](https://medium.com/@jitbit/target-blank-the-most-underestimated-vulnerability-ever-96e328301f4c.
A Loading Spinner
While the AJAX request is pending, show a loading indicator on the screen using one of these CSS spinners. Be sure to change the foreground color to something other than white if your app has a white background.
Tips
- The JSON response for this API is more complicated than the one we used in class. Once you get the data, use
console.log()
to access each property in the JSON. If you do it one property at a time, it'll be easier to identify if you make a mistake. - Install the JSON Viewer Chrome Extension to pretty print JSON responses in the browser