How do I use AJAX/JSON to manipulate the webpage
// Information to reach API
const url = 'https://api.datamuse.com/words?’;
const queryParams = ‘rel_jjb=’;
const additionalParams = ‘&topics=’;
// Selecting page elements
const inputField = document.querySelector(’#input’);
const topicField = document.querySelector(’#topic’);
const submit = document.querySelector(’#submit’);
const responseField = document.querySelector(’#responseField’);
// AJAX function
const getSuggestions = () => {
const wordQuery = inputField.value;
const topicQuery = topicField.value;
const endpoint = ${url}${queryParams}${wordQuery}${additionalParams}${topicQuery}
;
const xhr = new XMLHttpRequest();
xhr.responseType = ‘json’;
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderResponse(xhr.response);
}
}
xhr.open(‘GET’, endpoint);
xhr.send();
}
// Clear previous results and display results to webpage
const displaySuggestions = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
getSuggestions();
}
submit.addEventListener(‘click’, displaySuggestions);
I didn’t have a problem writing this code through the interactive lesson, but I’m struggling to completely understand it.
I’ve watched a few online tutorials running through AJAX/JSON so I understand where the new objects and methods are coming from and how they work.
However, I haven’t been able to get my code to affect the website in the lesson, even though I’m not getting any errors.
I’ve kept trying to place a word inside my “const inputField = document.querySelector(’#input’);” #input value to get an affect on the webpage, and nothing shows up.
If you’ve gotten this exercise to work, could you explain where you put your input value and what you manipulated?
I’m sure I’m making this more complicated than it is, but, when I run this exact code, no matter what I type into the website beside the lesson, nothing shows up.
So am I missing an input value somewhere? And if so where does it go?
Thanks in advance for any response.