Search code examples
javascriptjqueryjsonajaxgetjson

Querying json using getJSON displays "undefined" instead of data


I'm trying to use getJSON with jQuery, get the URL of an image and display it on this webpage.

The URL of the API works (shows a json), and the images exist, but "undefined" is displayed instead.

Any ideas?

<script type = "text/javascript" language = "javascript">
  $(document).ready(function() {

    $("#driver").click(function(event){

      $.getJSON("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=2015-6-3&api_key=API_KEY", {data: "value"}, function(json) { 
        $('#stage').html('<img src="' + json.photos.img_src + '">');
        $('#stage').append('<img src="' + json.photos.img_src + '">');
        $('#stage').append('<p> ID: ' + json.photos.id+ '</p>');
      })
    });
  });
</script>


Solution

  • Because it returns an array and you do not reference an element from the array

    $(document).ready(function() {
    
        $("#driver").click(function(event){
    
          $.getJSON("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=2015-6-3&api_key=cypvw52ysZT16N9HAFuh5bEDXb8lvDmw90ff4v26", {data: "value"}, function(json) { 
            //$('#stage').html('<img src="' + json.photos[0].img_src + '">');
            $('#stage').append('<img src="' + json.photos[0].img_src + '">');
            $('#stage').append('<p> ID: ' + json.photos[0].id+ '</p>');
          })
        });
      });
    
    
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="stage"></div>
    <button id="driver">test</button>