I would like to grab data which has a name tag by calling JSON data by using Ajax. But now a function showCard does not work correctly. How can I get the data which has a name tag? When you click a img which hasfound, I would like to grab data from an API, and show its name by innerHTML. But now nothing happens when you click it.
p.s. Its id is added in the function populatePokedex. Hopefully, this question makes sense. Thanks.
(function() {
'use strict';
window.onload = function(){
populatePokedex(); // <- This works correctly
var $foundPics = document.getElementsByClassName("found");
for(var i = 0; i < $foundPics.length; i++){
$foundPics[i].onclick = showCard;
}
};
// populate Pokedex
function populatePokedex() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
xhr.onload = function(){
if (this.status == 200) {
var picArr = this.responseText.split("\n");
for(var i=0; i < picArr.length; i++){
var eachName = picArr[i].split(":");
var spriteurl = "/Pokedex/sprites/" + eachName[1];
var imgClass = 'sprite';
if(eachName[1]==='bulbasaur.png' || eachName[1]==='charmander.png' || eachName[1]==='squirtle.png'){
imgClass += ' found';
} else {
imgClass += ' unfound';
}
document.getElementById("pokedex-view").innerHTML += "<img src=\"" + spriteurl + "\" id=\"" + eachName[0] + "\" class=\"" + imgClass + "\">";
}
} else {
document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
}
};
xhr.onerror = function(){
document.getElementById("pokedex-view").innerHTML = "ERROR";
};
xhr.send();
}
// if the pokemon is found, it shows the data of the pokemon
function showCard() {
var xhr = new XMLHttpRequest();
var url = "https://webster.cs.washington.edu/pokedex/pokedex.php?pokemon=" + this.id;
xhr("GET", url);
xhr.onload = function(){
var data = JSON.parse(this.responseText);
var pokeName = document.getElementsByClassName("name");
for(var i=0; i < pokeName.length; i++){
pokeName[i].innerHTML = data.name;
}
};
xhr.onerror = function(){
alert("ERROR");
};
xhr.send();
}
})();
Part of HTML is listed below;
<div id="my-card">
<div class="card-container">
<div class="card">
<h2 class="name">Pokemon Name</h2>
<img src="icons/fighting.jpg" alt="weakness" class="weakness" />
</div>
</div>
</div>
<!-- You populate this using JavaScript -->
<div id="pokedex-view"></div>
datalike this:var data = JSON.parse(this.responseText);?showCardmethod callled? becausepopulatePokedexhas async http request inside it.idinside your click event listener. instead of aforloop to assign click events, use an event listener like thisdocument.querySelector('.found').addEventListener('click', showCard)to assign that listener to every<div class="found"></div>