0

I have a problem with javascript array when passing into another object array. I have tried everything I came out on net, but nothing is working.

Problem is in line when fetching data from api on dataValues[dataValues.length] = (v.potroseno_tekucine);. Its working with labelValues. When I alert data in loop its ok, but when it needs to be processed it looks like its undefined. But when I, for example, alert(dataValues.length) before var data, its working ok.

$(document).ready(function () {
var ctx = document.getElementById("PodrumarstvoDetalji").getContext("2d");
var labelValues = [];
var dataValues = [];
$.ajax({
    url: root + "api/StatistikaApi/GetPodrumarstvoChart/?vinograd_id=10",// + $("#vinograd_id").val(),
    type: "Get",
    contentType: 'json',
    dataType: 'json',
    success: function (data) {
        $.each(data, function (k, v) {
            labelValues[labelValues.length] = v.opis;
            dataValues[dataValues.length] = (v.potroseno_tekucine);
        });
    },
    error: function (msg) { alert(msg); }
});
var data = {
    labels: labelValues,
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#ddd",
            pointHighlightFill: "#ddd",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: dataValues
        }/*,
        {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#ddd",
            pointHighlightFill: "#ddd",
            pointHighlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }*/
    ]
};


var myLineChart = new Chart(ctx).Line(data);
});

Can anyone help me please? I have tried with push, slice, concat but nothing...

The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
Veki
  • 117
  • 2
  • 9
  • 1
    possible duplicate of [Returning value from asynchronous JavaScript method?](http://stackoverflow.com/questions/6211023/returning-value-from-asynchronous-javascript-method) – doldt Jul 14 '15 at 19:33
  • 1
    One thing I would recommend is using `myArr.push(x)` instead of `myArr[myArr.length] = x`. I doubt it makes a difference here but it is a better practice in general. Another possibility is to declare a separate function and call it from the "on success" rather than doing the code directly in there. – nurdyguy Jul 14 '15 at 19:40
  • Tried it as well, it didn't help much. Its because code for chart was outside the success function. – Veki Jul 14 '15 at 19:47

1 Answers1

1

Ajax calls are asynchronous... this mean the data will be set before getting any response from your ajax request.

In order to fix this, you need to create your data in the ajax success callback function:

$.ajax({
    success: function (data) {
        $.each(data, function (k, v) {
            labelValues.push(v.opis);
            dataValues.push(v.potroseno_tekucine);
        });
        var data2 = {
          labels: labelValues,
          //...
        };
        //Insert your logic here to handle data2
    }
});
The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
  • Why labelValues is ok then? And why is ok when I call alert(dataValues.lenght) or alert(dataValues[0])? – Veki Jul 14 '15 at 19:38
  • It's only a matter of when you check those values. – The_Black_Smurf Jul 14 '15 at 19:40
  • its checked few lines before out of the success function. I have moved it in success and now its woking ok. Thank you for your help – Veki Jul 14 '15 at 19:46
  • @Veki - Don't use `alert()` for debugging, especially not for debugging asynchronous code, because it changes the timing of operations and can mislead you. Use `console.log()` and your browser's developer tools instead. Here's an introduction to the [Chrome DevTools](https://developer.chrome.com/devtools); other browsers have similar tools. – Michael Geary Jul 14 '15 at 19:51
  • I have tried with some console.log() debugging but didnt help me. I will go thru this link. Thank you – Veki Jul 14 '15 at 19:53
  • Glad to help, that's a good writeup. One nice thing about `console.log()` - it makes it convenient to add multiple log statements without having to click OK on each one. For example, in your code if you sprinkled `console.log()` calls throughout - particularly one in your `success` callback and another just before the `var data =` you'd see right away that the `var data =` was executed first. (I know you've already fixed the issue; this is just an example for future reference.) – Michael Geary Jul 14 '15 at 19:58
  • You can also do this with breakpoints without having to modify the source code. In this example you'd set a breakpoint inside the `success` callback and one on the `var data =` and you could see where it stops first. Breakpoints and the JavaScript debugger are really great because you can look around at all your data without having to write explicit logging code for every variable. – Michael Geary Jul 14 '15 at 20:02