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

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...

Invoking a nested method within Vue.js

I am facing an issue in my vuejs application with 2 methods. When I define method1 a certain way, it does not run as expected. method1: function(param1, param2){ // I can log param1 here thirdLib.debounce(function(param1, params2){ // It d ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

Ways to verify the identity of a user using an external authentication service

One of my microservices deals with user login and registration. Upon making a request to localhost:8080 with the body { "username": "test", "password":"test"}, I receive an authentication token like this: { "tok ...

Using a Javascript hyperlink to trigger a POST request in Python

I am currently developing a web scraping and automation tool that requires the use of POST requests to submit form data. The final action involves using the following link: <a id="linkSaveDestination" href='javascript:WebForm_DoPostBackWithOptions ...

Tips for utilizing setState to display specific information fetched from an API call through the mapping method

Is there a way to utilize setState in order to render individual data retrieved from an API call? Despite my efforts, all I seem to get is another array of data. Here's the code snippet: const [likes, setLikes] = useState(0); useEffect( async () = ...

How to transform a JSON array into individual object properties using jQuery?

In my JSON data, the structure looks like this: [ { "name": "object1", "prop": "prop1", "props": [ { "prop1": "value1" }, { "prop2": &quo ...

Error: Call stack size limit reached in Template Literal Type

I encountered an error that says: ERROR in RangeError: Maximum call stack size exceeded at getResolvedBaseConstraint (/project/node_modules/typescript/lib/typescript.js:53262:43) at getBaseConstraintOfType (/project/node_modules/typescript/lib/type ...

Generate a JSON object specifically for the modified input fields upon submitting the form

Is there a way to generate a JSON object only with the input fields that have been modified before submitting the form? How can I capture and store each changed value in the form as JSON data? $(document).ready(function() { $('#save').clic ...

Inadequate speed and efficiency in Javascript and JQuery operations

I'm facing severe lag problems in my JavaScript code, particularly with the parallax effects being very slow. I suspect this is due to multiple executions of functions. Below is the code snippet: function tada() { $(".arrow").addClass("tada"); s ...

Using jQuery with an update panel

What is the reason that jQuery tools do not function properly within an UpdatePanel? I have created a jQuery calendar that works fine, but when placed inside an UpdatePanel it stops working. ...

The HTTP request is malfunctioning in a different location

I'm facing an issue where my code works in the w3schools code editor, but not on localhost or cpanel host. When I try to run it on another host, it gives me a bad request and doesn't return the answer. Here is the code snippet that I am working ...

Tips for updating the content of multiple tabs in a container with just one tab in Bootstrap 4.x

I am attempting to create two tab containers, where one is used to describe the content of a set of files and the other is used as a list of download links for the described files. Initially, I tried controlling the two containers using just one tab. I ca ...

The MUI multiple select feature is experiencing issues following the addition of a new button

I'm having trouble adding buttons below a select dropdown menu with a specific height. When I try to put the menu item inside a div, the multiple select stops working and I have no idea why. Can someone help me figure this out? Check out my CodeSandb ...

Trouble displaying JSON data in HTML using *ngFor in Angular

Just starting out with angular and I've created a services class that returns product details in JSON format. api.service.ts import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/ ...

Tips for excluding certain parameters in the jslint unparam block

While developing my angular app, I encountered an issue with jslint flagging an unused parameter. Typically in angular, the "$scope" is required as the first parameter in your controller definition. In my case, I prefer using the "this" keyword instead of ...

Is it possible to bulk update a sorted set using the Redis client in Node.js?

Looking to update multiple records in a sorted set using Redis client in Node.js. Currently, I am able to update a single record with client.zAdd(key,{score:score, value:memberId}). Is there a command or function that allows for bulk updates in Redis? I se ...

Utilizing jQuery to execute functions from various files simultaneously with a single load statement

My goal is to achieve a basic include with jQuery, which involves loading functions from multiple files when the DOM is ready. However, this task proved to be more complex than anticipated: index.html <script type="text/javascript" src="res/scripts.js ...

Use jQuery ajax to send form data and display the received information in a separate div

I'm working on a PHP test page where I need to submit a form with radios and checkboxes to process.php. The result should be displayed in #content_result on the same page without refreshing it. I attempted to use jQuery Ajax for this purpose, but noth ...

What is the best way to swap out particular phrases within HTML documents or specific elements?

Trying to update specific strings within an HTML document or element. How do I go about parsing and replacing them? To clarify: - Identify all instances of #### in element .class - Swap them out with $$$$$ Currently utilizing jQuery for this task. Appre ...