Search code examples
javascriptjqueryajaxjsonp

JSONP using .getJSON is returning undefined


I'm trying out an exercise in Learning jQuery 4th edition by Karl Swedburg for Ajax, and more specifically JSONP.

My code is

$(document).ready(function(){
var url='https://api.github.com/users/jquery/repos';
$.getJSON(url + '?callback=?',function(data){
  var content='';
  $.each(data,function(index,item){
    content +='<div class="userdata">';
    content +='<div class="username">'+item.id+'</div>';
    content +='<div class="username">'+item.name+'</div>';
    content +='<div class="userurl">'+item.url+'</div>';
    content +='</div>';
  });
  $('#dictionary').append(content);

});
});

I've checked the developer tools and my request is returning status 200

and an extract of the data returned from the request is as shown below

{
  "id": 5999890,
  "name": "2012-dev-summit",
  "full_name": "jquery/2012-dev-summit",
  //more stuff
}

I've checked and double checked my code and can't seem to figure out why is it returning undefined.

EDIT:Added what is appended

undefined
undefined
undefined
undefined
undefined
undefined

i get 6 undefined,which would equate to 2 iterations seeing as outputting 3 items per round, ie. id,name and url.


Solution

  • Try the below. You are getting the result in result.data object. Not in result object.

    $(document).ready(function(){
    var url='https://api.github.com/users/jquery/repos';
    $.getJSON(url + '?callback=?',function(result){
      var content='';
      var data = result.data;
      $.each(data,function(index,item){
        content +='<div class="userdata">';
        content +='<div class="username">'+item.id+'</div>';
        content +='<div class="username">'+item.name+'</div>';
        content +='<div class="userurl">'+item.url+'</div>';
        content +='</div>';
      });
      $('#dictionary').append(content);
    
    });
    

    });

    FIDDLE