Skip to content

Instantly share code, notes, and snippets.

@bryancodesjs
Created January 21, 2022 20:02
Show Gist options
  • Save bryancodesjs/89c9a41eeb14b3bf7582bffae6e23f7a to your computer and use it in GitHub Desktop.
Save bryancodesjs/89c9a41eeb14b3bf7582bffae6e23f7a to your computer and use it in GitHub Desktop.
retrieve data from an API using XMLHttpRequest and then iterate over the results
//API url
const quotesUrl = 'https://quote-garden.herokuapp.com/api/v3/quotes'
//my function
function myRequest() {
//initialize an instance of the XMLHttpRequest object
const req = new XMLHttpRequest();
//set the parameters to be used in the get request
req.open("GET", quotesUrl, true);
//send the get request
req.send();
//once a response is received, execute this function
req.onload = function() {
//parse the json response. I'm only interested on the 'responseText', so I'll only parse that
let chunk = JSON.parse(req.responseText);
//save the length of the array
let chunkLength = chunk.data.length;
//iterate over the array 'x' amount of times, where 'x' is equal to the array length
for(var i = 0; i < chunkLength; i++) {
//I'm selecting a specific value from every object: the quoteText
let item = chunk.data[i].quoteText;
//log the value or do XYZ with it
console.log(item);
}
}
}
//invoke the function
myRequest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment