Build this assignment in CodeSandbox.
For this assignment, you will build a dad joke search application using the icanhazdadjoke API.
The Search Form
At the top of the page, create a form with a single search input and a submit button. When a user submits the form, make an AJAX request using the fetch
function to get a list of dad jokes that match the value that was typed into the search box. For example, if a user types in "cat", make an AJAX request to https://icanhazdadjoke.com/search?term=cats&page=1. If a user submits the form without typing a search term, make an AJAX request to https://icanhazdadjoke.com/search?term=&page=1.
Unlike other APIs we've used in this class, this API requires sending the Accept
HTTP header. For example:
fetch("https://icanhazdadjoke.com/search?term=cats", {
method: "GET",
headers: { Accept: "application/json" },
})
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
});
This API uses the Accept
header to determine the format it should respond with. Setting the Accept
header to application/json
tells the API to respond with JSON.
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 and there are results (results
isn't an empty array), render the following using Handlebars:
- Render
total_jokes
at the top of the results. - Render each
joke
withinresults
. - Render
current_page
andtotal_pages
underneath the list of dad jokes. - Add Previous Page and Next Page buttons underneath the list of dad jokes so a user can paginate the results. Use the
previous_page
andnext_page
properties. Most of the search terms only return a single page. When this happens, theprevious_page
andnext_page
properties contain the value 1. It is fine if clicking these buttons just search for page 1 again. If you submit the form without a search term, you will get back a result set that contains multiple pages. You can also search for "the" and you'll get a result set that contains multiple pages.
If there are no results (results
is an empty array), simply render a paragraph with the text "No results found".
A Loading Spinner
While an AJAX request is pending (during initial load and paginating results), show a loading indicator on the screen using one of these CSS spinners. Put the HTML for this loading spinner in a separate Handlebars template. Be sure to change the foreground color to something other than white if your app has a white background.
Submission
Send an email to me and the TA with your CodeSandbox link. Use "ITP 404 - Assignment 2" as the email subject.