Kyriediculous
Kyriediculous

Reputation: 119

jQuery AJAX Request returning different JSON than expected

I'm trying to request a json file through AJAX (jQuery) from NBA.com

I tried first getting the json file but got a CORS error so I tried using jsonp

This returns me an object but the object looks like it's full of functions and methods instead of the data I requested.

I made this on codepen so you can check it out, output can be checked with developer console because document.write just returns [object Object]

here is the link to codepen: http://codepen.io/kyriediculous/pen/KNKZZL

$(document).ready(function() {

function getPlayerGameLogs() {

  $.ajax ({
url: "http://stats.nba.com/stats/commonplayerinfo?LeagueID=00&PlayerID=202355&SeasonType=Regular+Season&format=jsonp",
dataType:"jsonp",
success: function(response) {
  console.log(response);
}
  })

};
  getPlayerGameLogs();
});

Could someone explain this a bit ? Is it impossible to request the JSONs from nba.com? Specifically the game logs for every player.

Upvotes: 0

Views: 203

Answers (1)

Dan Wilson
Dan Wilson

Reputation: 4057

Your example works just fine.

$(document).ready(function() {
  
function getPlayerGameLogs() {
  
  $.ajax ({
    url: "http://stats.nba.com/stats/commonplayerinfo?LeagueID=00&PlayerID=202355&SeasonType=Regular+Season&format=jsonp",
    dataType:"jsonp",
    success: function(response) {
      console.log(response.resultSets);
      populateTable(response.resultSets, 'CommonPlayerInfo');
      populateTable(response.resultSets, 'PlayerHeadlineStats');
    }
  })
  
};
  getPlayerGameLogs();
});

function populateTable(resultSets, setName) {
  var data = resultSets.filter(function(set){
    return set.name === setName;
  })[0];
  var headers = data.headers;
  var rowSet = data.rowSet;
  var table = $('#' + setName);
  var tr = table.append($('<tr>'));
  $(headers).each(function(){
    tr.append(tr.append($('<th>').text(this.toString())));
  });
  $(rowSet).each(function(){
    var tr = $('<tr>');
    this.forEach(function(item){
      tr.append($('<td>').text(item.toString()));
    });
    table.append(tr);
  });
}
body {
  font-family: sans-serif;
}

table {
  border: 1px solid gray;
  font-size: 11px;
  border-collapse: collapse;
}

td, th {
  border: 1px solid gray;
  padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head></head>
  <body>
    <h3>Headline Stats</h3>
    <table id="PlayerHeadlineStats"></table>
    <br />
    <h3>Player Info</h3>
    <table id="CommonPlayerInfo"></table>
  </body>
</html>

Upvotes: 3

Related Questions