FAQ: Requests I - XHR GET Requests IV

Community%20FAQs%20on%20Codecademy%20Exercises

This community-built FAQ covers the “XHR GET Requests IV” exercise from the lesson “Requests I”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise XHR GET Requests IV

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

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.

3 Likes

hi geena
copy and paste the following and see if this works:-

// 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);

Your code is missing some backticks here:

const endpoint = ${url}${queryParams}${wordQuery}${additionalParams}${topicQuery};

it should be

const endpoint = `${url}${queryParams}${wordQuery}${additionalParams}${topicQuery}`;

Does that fix it?

1 Like

I had the same problem and the backtick thing didn’t work. Although there are no errors, i am still not getting the result and i have no idea why.

// 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);

the last function displaySuggestions has a parameter (event),

  1. I read that it is a javascript object, if so, why is it necessary to define it as a parameter for this function? I tested it by removing the event parameter and things still worked the same though.
  2. This function has a while loop that detects if the first child element of the responseField, (that is the first item in the ordered list returned correct?), if it is not blank, then remove it, in this case if the output has 10 items, the while loop actually executes 10 times right?
  1. It confuses me, too. I looked it up and found a discussion about it. Some say that it could lead to a different result in a different situation. So I think it is just a good practice to pass the event as an argument.
    https://teamtreehouse.com/community/why-do-we-add-event-to-the-anonymous-function
    https://teamtreehouse.com/community/could-somebody-explain-the-use-of-the-event-parameter-used-in-the-function

  2. responseField.firstChild refers to the first child node of responseField.

let wordList = []

  for(let i = 0; i < Math.min(res.length, 10); i++){
    wordList.push(`<li>${res[i].word}</li>`)
  }

  wordList = wordList.join("")

  responseField.innerHTML = `<p>You might be interested in:</p><ol>${wordList}</ol>`

We can see here that responseField has two child nodes, which is <p> element and <ol> element. <ol> element has a number of child nodes <li> depending on the number of the results. So in this function, the while loop only runs twice, removing <p> element and <ol> element (and consequently, all of its child nodes).

Does the amazon and shopping website use same concept like when we search something they also suggest items with you might be interested in.

Yes I found this topic difficult to understand and only got there - am still getting there - by watching quite a lot of other tutorials outside of codecademy.

One question I have is, how do you know what to put in the queryParams? Does this depend on the API you’re using?

Yup, it depends on the API.
Codecademy linked the API source page where you can check the different parameters and their purpose.

Is there a reason why we don’t need to import the functions from helperFunctions.js into main.js?

I was under the assumption that the renderResponse callback won’t understand what to do if we don’t first export it from the other file.

Or, is it because they are in the same public directory, it will search there by default?

Thanks !