Need help with $.getJSON

Need help with $.getJSON
0.0 0

#1

Hey guys, I’m trying to write a function that retrieves a picture’s url using jQuery but I can’t get getJSON to pass on the info to the next get request which I believe is due to its asynchronous nature (which I admit I dont fully understand yet). I was hoping someone would be so kind as to help me understand this

let getImg = (id, artist) => {
  let imgMain =
    'https://en.wikipedia.org/w/api.php?action=query&titles=' +
    artist +
    '&prop=images&format=json&origin=*';

  $.getJSON(imgMain, function(data) {
    let imgKey = JSON.stringify(data.continue.imcontinue)
      .replace(id, '')
      .replace(/\|/g, '')
      .replace(/['"]/g, '');

    let imgJson =
      'https://commons.wikimedia.org/w/api.php?action=query&titles=File:' +
      imgKey +
      '&prop=imageinfo&&iiprop=url&origin=*';

    //NOT WORKING BELOW THIS LINE
    $.getJSON(imgJson, function(data) {
      let imgUrl = JSON.stringify(data.query.pages.id.imageinfo);
    });
  });
};

#2

Do you have any codepen link? Or a set of inputs that you know should work?


#3

I’m not 100% on the code in jQuery but there’s a method for waiting until the first part is done to execute the second. I believe it is $.when($.getJSON(1)).done($getJSON(2))


#4

I don’t have a Codepen for it but id: 51511 and artist: prince should work.


#5

Thanks for the reply! Oddly enough, I tried when, then, done, and success… with no success


#6

It looks like you forgot format=json in the second URL’s parameter list.

Here’s a screenshot of what the response looks like in Firefox’s devtools:


#7

Thanks. I made the change but still no luck


#8

Please post your latest code attempt, so we can take a look.


#9

I’ve finally gotten it to work! Thanks! As @kevcomedia pinted out I forgot to place in “format=json” and also my path to the image was wrong. Thanks again everyone!