This is quite a difficult problem to explain, but it probably comes from a misunderstanding of how javascript works with objects:
I'm trying to build a list of points over a period of several years: I have two date objects of which the year is incremented in each cycle.
I'm calling a function getPoint
that builds a point using the date objects, here's the code:
while(td2.getTime()<date2.getTime())
{
td1.setYear(td1.getFullYear()+1);
td2.setYear(td2.getFullYear()+1);
console.log(td1);
test=getPoint(sessionStorage.Link,stat,td1.getFullYear()+'-'+td1.getMonth()+1+'- '+td1.getDate(),td2.getFullYear()+'-'+td2.getMonth()+1+'-'+td2.getDate());
$.extend(points,test);
}
The getPoint function is this:
function getPoint(who,stat,date1,date2){
string=date1+"/"+date2;
var point={};
$.ajax({
type:'GET',
url: who +'/'+ stat + '/'+date1+'&'+date2,
data:{"token" : member.token},
dataType:'JSON',
error: function(){
point={};
},
success:function(data){
stat=stat.split('/');
stat=stat[1];
point[string]=data[stat];
}
});
return point;
}
At the end of the while loop I'm expecting points to ressemble:
points={date1/date2: value, date1+(1year)/date2+(1year) : value, ..., date1+(n years)/date2+(n years) : value}
Unfortunately I only get:
points = {date1/date2 : value, date1+nyears/date2+nyears : value}
Where n is the number of iterations.
To try and understand the problem, I've made this appear in the console and it appears to me that the function getPoint
is only getting called using the date object in it's state after the while loop has finished. Can anyone explain why this might be the case, if it is possible for it to be the case?
Edit I tried to replace my code with the following, but I still only get:
[Log] Object (mystats.js, line 61)
2015-2016: 0
__proto__: Object
in the log.
function getPoint(who,stat,date1,date2){
return $.ajax({
type:'GET',
url: who +'/'+ stat + '/'+date1+'&'+date2,
data:{"token" : member.token},
dataType:'JSON',
});
}
var td1=new Date(date1.getTime());
var td2=new Date(date1.getTime());
var points={};
td2.setFullYear(td2.getFullYear()+1);
getPoint(sessionStorage.Link,stat,td1.getFullYear()+'-'+(td1.getMonth()+1)+'-'+td1.getDate(),td2.getFullYear()+'-'+(td2.getMonth()+1)+'-'+td2.getDate()).done(function(result)
{
tStat=stat.split('/');
points[td1.getFullYear()+'-'+td2.getFullYear()]=result[tStat[1]];
});
while(td2.getTime()<date2.getTime())
{
td1.setYear(td1.getFullYear()+1);
td2.setYear(td2.getFullYear()+1);
getPoint(sessionStorage.Link,stat,td1.getFullYear()+'-'+(td1.getMonth()+1)+'-'+td1.getDate(),td2.getFullYear()+'-'+(td2.getMonth()+1)+'-'+td2.getDate()).done(function(result){
tStat=stat.split('/');
var newPoint={};
newPoint[td1.getFullYear()+'-'+td2.getFullYear()]=result[tStat[1]];
$.extend(points,newPoint);
});
}
Update : This is because the date objects have changed before the callback is called.. my question is therefore how can I make sure that the callBack uses the object in it's state when the original AJAX call is called?