0

I have made the following function for getting data from my database.

            function getData() {
            var array = [];
            var clickBtnValue = "getInteractive";
            var ajaxurl = '../crawler/function/statistic_func.php',
                    data = {'action': clickBtnValue, 'intervalHour': "1", 'value': "main_tag", 'valueEqualTo': searchTag};
            $.get(ajaxurl, data, function (response) {
                // Response div goes here.
                objIntChart = JSON.parse(response);
                objIntChart.forEach(function (entry) {
                    array.push([entry['dateTime'], entry['entries']]);
                });
                console.log(array);
            });
            console.log(array);
            return array;
        }

My first console.log(array); prints out the array exactly how it is supposed to be.

The second console.log(array); prints out an empty array. I am not sure why this is the case when I have initialised the array in the beginning of the function?

  • Ajax works asynchronously. So the call to console outside of `$.get` call might be executed before ajax call is completed, thus giving you an empty array. There is way to tell jquery to make sync call though, if that's what you want, but it kind of defies the purpose of ajax – Andrei Sep 17 '15 at 12:25
  • lol, beat me to this answer by like 10 seconds. :D – Jason Sep 17 '15 at 12:26
  • I've been sitting with this for like 4-5 hours. So my brain is not fully functional right now ;) The function getData() gets called constantly. Since I constantly need to get the array updated for an interactive chart. What would be a good solution to do this? – Andreas Uldall Leonhard Sep 17 '15 at 12:34

0 Answers0