I have this code which retrieves JSON using $.getJSON()
from 2 URLs and saves the results as variables. I then use $.when()
and then()
to get the data from these variables. However, this only works when I do one at a time, each with it's own $.when()
, and does not work when I use both.
var player = $.getJSON("http://api.hivemc.com/v1/player/" + $user + "/timv");
var game = $.getJSON("http://api.hivemc.com/v1/game/timv");
$.when(player,game).then(function(maindata, data){
$('#1').text(maindata.total_points);
$('#2').text(maindata.i_points);
$('#3').text(maindata.t_points);
$('#4').text(maindata.d_points);
$('#5').text(maindata.role_points);
$('#6').text(maindata.most_points);
if(maindata.detectivebook == true)
$('#7').text("Yes");
else
$('#7').text("No");
$flare = maindata.active_flareupgrade;
$flare = $flare.charAt(0).toUpperCase() + $flare.slice(1).toLowerCase();
$('#8').text($flare);
$('#9').text(maindata.title);
var d = new Date(maindata.lastlogin * 1000);
var n = d.toISOString();
$('#10').text(d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear());
});
The console error I get is:
jquery-latest.min.js:2 Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-latest.min.js:2) at Object. (dr:112) at Function.each (jquery-latest.min.js:2) at Object. (dr:108) at Object. (jquery-latest.min.js:2) at j (jquery-latest.min.js:2) at Object.fireWith [as resolveWith] (jquery-latest.min.js:2) at x (jquery-latest.min.js:4) at XMLHttpRequest.b (jquery-latest.min.js:4)`
Can anyone tell me what I am doing wrong? Thanks.
Ok here is the reason why: when you use then
, the params you declare in your success function are not the data itself, but an array containing the data, the status string and the XHR object. So in your case maindata
gets [Object, "success", Object]
.
Replace this part of the code with the following and it should work (additionnally, maybe there should be a check to do on the status before getting the data):
$.when(player,game).then(function(mainresponse, response){
var maindata = mainresponse[0];
var data = response[0];