82 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2021-03-31 21:56:49 -04:00
"use strict"
window.addEventListener("DOMContentLoaded", function () {
document.querySelector("#fetchQuotesBtn").addEventListener("click", function () {
// Get values from drop-downs
const topicDropdown = document.querySelector("#topicSelection");
const selectedTopic = topicDropdown.options[topicDropdown.selectedIndex].value;
const countDropdown = document.querySelector("#countSelection");
const selectedCount = countDropdown.options[countDropdown.selectedIndex].value;
// Get and display quotes
fetchQuotes(selectedTopic, selectedCount);
});
});
function fetchQuotes(topic, count) {
// TODO: Modify to use XMLHttpRequest
// TODO: set request type to expect json
// the api https://wp.zybooks.com/quotes.php?topic=love&count=3
let url= "https://wp.zybooks.com/quotes.php?";
let xhr = new XMLHttpRequest();
xhr.responseType = "json";
//Let the user select what to do
let topicOption = document.querySelector("#topicSelection");
topicOption = topicOption.options[topicOption.selectedIndex].text;
let countSelection = document.querySelector("#countSelection");
countSelection = countSelection.options[countSelection.selectedIndex].text;
url+= "topic=" + topicOption + "&count=" + countSelection;
xhr.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE) {
responseReceivedHandler(this.response);
}
}
xhr.open("GET", url, true);
xhr.send();
}
/* TODO: Add responseReceivedHandler() here
receives request response displays quotes in an ordered list
should be as follows:
let html = "<ol>";
for (let c = 1; c <= count; c++) {
html += `<li>Quote ${c} - Anonymous</li>`;
}
html += "</ol>";
document.querySelector("#quotes").innerHTML = html;
If the response is an error, it should instead be:
Topic 'TOPIC_VAR' not found
*/
function responseReceivedHandler(response){
console.log(response);
let html;
if (response.error){
html = response.error;
}
else{
html = "<ol>";
for (let i = 0; i < response.length; i++){
html+= "<li>" + response[i].quote + " - " + response[i].source;
}
html += "</ol>";
}
document.querySelector("#quotes").innerHTML = html;
}