Extracting information from a JSON data within an API

How can I retrieve data with a name tag from JSON data using Ajax? The function showCard is not functioning properly when I try to grab data with a name tag. My goal is to display the name of the API data when an img element with the class found is clicked, but currently nothing happens when clicked. p.s. The id is added in the populatePokedex function. Hopefully this question makes sense. Thank you.

(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>

Answer №1

You seem to be facing some problems in your JavaScript code for the showCard function

To help you out, I've come up with a simple solution along with explanatory comments within the code

(function() {
  'use strict';

  window.onload = function() {
    populatePokedex(); // <- This function works correctly
    
    // adding event listeners for dynamically added elements.
    
    
 document.querySelector('body').addEventListener('click', function(event) {
      
      if (event.target.className.toLowerCase().indexOf('founded') != -1) {
        showCard();
      }
    });
  };


// function to 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 = "https://webster.cs.washington.edu/pokedex/sprites/" + eachName[1];
          var imgClass = 'sprite';
          if (eachName[1] === 'bulbasaur.png' || eachName[1] === 'charmander.png' || eachName[1] === 'squirtle.png') {
            imgClass += ' founded';
          } 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();
  }

  function showCard() {
    
    var xhr = new XMLHttpRequest();
  
    var url = "https://webster.cs.washington.edu/pokedex/pokedex.php?pokemon=" + event.target.id;

    xhr.open("GET", url);
    xhr.onload = function() {
   
      var data = JSON.parse(this.responseText);

      document.getElementById("pokemon-name").innerHTML = data.name;
    };
    xhr.onerror = function() {
      alert("ERROR");
    };
    xhr.send();

  }




})();
.founded:hover {
  cursor: pointer;
}

.founded {
  border: 1px solid green;
}
<div id="my-card">

  <div class="card-container">
    <div class="card">
      <h2 id="pokemon-name" class="name">Pokemon Name</h2>
      <img src="https://webster.cs.washington.edu/pokedex/icons/fighting.jpg" alt="weakness" class="weakness" />
    </div>
  </div>
</div>

<!-- You can populate this container using JavaScript -->
<div id="pokedex-view"></div>

Answer №2

After entering your specific url link: , I retrieved this insightful information:

{"title":"Pikachu","cp":180,"details":{"id":"025","characteristic":"electric","vulnerability":"ground","note":"It occasionally discharges electricity when it's dozing off."},"visuals":{"image":"illustrations\/pikachu.jpg","typeSymbol":"symbols\/electric.jpg","vulnerabilityIcon":"icons\/ground.jpg"},"techniques":[{"name":"Thunder Shock","style":"electric"},{"name":"Quick Attack","power":80,"style":"normal"}]}

If you wish to showcase the term "Pikachu", either data.title or data['title'] will suffice. I suspect that there might be an issue with

document.getElementsByClassName("name").innerHTML
. Could you share any error messages shown during the function execution, or provide a snippet of your HTML code?

Answer №3

Instead of using the code below to define the "click" action

$foundPics[i].onclick = showCard;

It is recommended to attach an event listener like this

$foundPics[i].addEventListener('click', showCard());

Additionally, your xhr.open() method should be placed before the send() call for standard usage.

I hope you find this information helpful

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through an array of functions, some of which may return promises while others do not

Is there a way to efficiently iterate and execute an array of functions where some return promises, requiring the use of await, while most do not return promises, necessitating them to be set as async? for (let i = 0; i < this.steps.length; i++) { ...

What is the process for loading Syntax Highlighter on pages with pre tags?

As a Blogger, I often find myself in need of demonstrating codes on my blog. To achieve this, I have been using a Syntax Highlighter developed by Alex Gorbatchev. However, a recurring issue I face is that the files load on every single page of my blog, cau ...

Utilizing sessions in Node.js Express3 to verify user's authentication status

Here is the content of my app.js file: app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine&apo ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Is it possible to Use Vuejs 2 to Update MathJax dynamically?

Just figured out how to resolve this issue. Simply bind the data using v-html <div id="app"> <h1 v-html="equation"></h1> <button @click='change'>Change</button> </div> var vm ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

Terminate a targeted recipient following the completion of the on event

I am currently running a node service with socket.io and utilizing an event emitter to send updates based on user context. For example, context A may have users 1, 2, and 3 while context B has users 4 and 5. Once a successful connection is established wit ...

How to effectively utilize the Twitter API with C# - a comprehensive guide

Seeking guidance on utilizing the Twitter API with C#. Currently struggling to find relevant information. ...

I am currently studying JavaScript. The syntax of my if statement with && appears to be accurate, however

I'm having trouble with the logic in my "Code your Own Adventure" program on Code Academy. I expect it to display "Great, come get your pizza!" when I enter PIZZA, YES, and YES as prompts, but instead it says "NO pizza for you!" I've tried using ...

Using jQuery to enhance the functionality of the drop-down select feature

I am facing an issue with my index file code. When I select something from the drop-down menu, I expect to see a related dropdown appear. Although I have added this code to my file, I am unable to get the drop down to show after selecting the main type. ...

Utilize socket communication with node.js to monitor and identify user

I'm attempting to find a method to unsubscribe from a Redis channel when the user navigates to another page within our website. I have attempted to detect a disconnect socket event when the user clicks on a link, but unfortunately, the event is never ...

Issue encountered: Trying to deploy firebase functions and hosting with vue-cli v3 and node.js leads to an error "No npm package found in functions source directory

My plan is to utilize Vue.js for the Frontend and Firebase Functions (Express.js) + Firestore for the Backend. Step 0: I initiated a new project on Google Firebase, then created a new Service Account with Owner's permissions to be used with Admin SDK ...

What is the process for sending an array to a Jenkins parameterized job using the remote access API?

I need assistance in calling a Jenkins parameterized job using the curl command. I am referring to the Jenkins Remote API documentation. The job involves an Active choice parameter plugin with one parameter being an Active choice reactive parameter. Atta ...

Guide to updating information in Firestore using Node.js, embedded in a map array

Encountered an issue with the following error message: Error: Unable to access 'set' property of undefined. I am attempting to update the endTime field in my script for each user, calculate total hours worked, and then update the 'totalTi ...

Add Content to Textbox by Clicking

In my current setup, I have a variety of buttons that, when clicked, should add the text from the button to a text box. Each time a button is clicked, I want the text to be appended to whatever is already in the input field. Current Approach $('#js- ...

Struggling with Internet Explorer?

My script is working perfectly on all browsers except for Internet Explorer. The script refreshes the page to display a chat, but it seems to be causing issues in IE. Do you have any suggestions on how to make this work specifically for Internet Explorer? ...

Share your content on Facebook with just a click of a button and automatically

Hey there, I'm facing a bit of a dilemma. I want to share a page on Facebook that contains a picture gallery with a unique URL that allows the gallery to load up the correct image based on the thumbnail selected. However, when Facebook scans the HTML ...

Running a JavaScript function on an external site using C#

I'm having trouble downloading an image from an external site using C#. The issue is that the image's source is generated server-side with ajax and isn't accessible from the page's source code. The JavaScript function responsible for ge ...

ASP.NET AJAX UpdatePanel - preventing postback in InitializeRequest will not reset back to enabled state

In my ASP.NET AJAX UpdatePanel, there is a submit button with custom javascript validation that sets a global flag called _cancelGeneralSettingsUpdate based on the validation results. Everything works fine except when an invalid value is entered, correcte ...

Material-UI: The Mystery of Missing CSS Properties

Struggling to apply a CSS class to an element from Material-UI: bw:hover { -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */ filter: grayscale(100%); } Tried using makeStyles: import { makeStyles } from '@material-ui/core/styles' ...