0

I'm trying to retrieve a specific ID from the JSON file depending on user input and then display a picture based on the ID retrieved from the JSON file

function showCard() {
    var cardNaqme = document.getElementById('un').value;
    var cardNameProper = cardName.replace(/\s/g, '');
    var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
    var imgId = obj["data"][0]["id"]
    document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
    event.preventDefault();
}
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95

2 Answers2

0

I think what you need is below but I am not sure I understood your json structure:

var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var oReq = new XMLHttpRequest();
oReq.open("GET", "https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper", true);
oReq.responseType  = "json";
oReq.onload = function(e) {
      JSONObject json = new JSONObject(res);
      JSONArray ja = json.getJSONArray("data");
      JSONObject obj = ja.getJSONObject(0);
      var imgId = obj.id;
      document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
}
oReq.send();
            
codelch
  • 33
  • 7
0

I tried to answer your problem after identifying your problem.

function showCard()
{
event.preventDefault();
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
var imgId = obj[0].id
document.getElementById("chosenCard").src = 
"https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jpg";
}