1
Person, I need help with a call from an API, which returns a JSON.
I’ve tried several things, but I can’t get the information back in my HTML.
Can anyone support me with some code? I didn’t put here what I used because I used several.
I just need to get the name and the Description. I’ve used the direct name, I used values.name, but nothing worked.
An example of my javascript
var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', '');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
pageCounter++;
if (pageCounter > 10) {
btn.classList.add("hide-me");
}
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data.values[i].name + data.values[i].description;
htmlString += '.</p>';
}
animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
Thank you.
if you’re using
data.values[i].name
no for should bedata.values.length
– Ricardo Pontual