0

I'm pretty new to js.

I'm using flask in python to create a website. What I want to do is generate a chart using googlecharts and data from an sql database. In one of my urls, I'm "jsonifying" the data and attempting to access it in js via "$.getJSON" as follows:

var males;
var females;

$.getJSON("/getstats", function(data){
    for (obj of data){
        males=obj.males;
        females=obj.females;
    }
});

But the variables' values aren't changing to equal obj.females and obj.males.

They do change to anything I assign them outside the $getJSON brackets.

I stumbled upon Variables set during $.getJSON function only accessible within function which seemed to be similar to my question; but I tried the solution within the question's "UPDATE #2" and it still didn't work.

How can I reach the values of obj.females and obj.males?

SMT
  • 1
  • How do you know, that values are not changed? I mean there's no code using the variables ... – Teemu Dec 30 '17 at 17:47
  • You're already reaching those values inside the callback. Since that's where you've had success in accessing the data, maybe that's where you should utilize the data. –  Dec 30 '17 at 17:48
  • The answer is in the thread you posted - not the question, but the answers. It’s not about where the code is, but **when** the code runs. – Mark Dec 30 '17 at 17:49
  • Also, it doesn't really seem to make sense to have a loop here; you will re-set `males` and `females` in each iteration. Are you sure the source data actually contains an array of objects? Maybe it is just a single object. – Daniel Roseman Dec 30 '17 at 17:49
  • how does `data` look like? – brk Dec 30 '17 at 17:51
  • @Teemu: I'm generating a chart using the value of the variables males and females. The values are not equal to obj.males/females. – SMT Dec 30 '17 at 17:54
  • 1
    I've a hunch you haven't fully understood how asynchronous requests work. See http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323 . Notice, that the provoded code works as it is, if you'd read the values of the variables in that callback function, they would have the values (last) assigned in the `for .. in ` loop. – Teemu Dec 30 '17 at 17:55
  • @DanielRoseman Oh god, you were right. It was a single object. ^^"" Thank you so much. In such cases should I just go ahead and delete my original post? – SMT Dec 30 '17 at 18:04

0 Answers0