0

I am creating a chart with nvd3. Since i am pretty new to javascript i've got a little problem assigning the chartdata. When i assign it like this:

var long_short_data = [
  {
    "key": "ISP",
    "color": "#d62728",
    "values": [
      {
        "label" : "oäop" ,
        "value" : 9000
      } ,...
    ]
  },
    {
    "key": "Organization",
    "color": "#d67548",
    "values": [
      {
        "label" : "amklöericalököky" ,
        "value" : 8000
      },...
    ]
  }
];

The graph is displayed as it should. But when i assign it like this:

var long_short_data = $.getJSON( "/link/to/multiBarHorizontalData.json", function() {
console.log( "success" );
}) 

It doesnt. These are my console logs:

success
nvd3.js:9229 Uncaught TypeError: data.map is not a function

Any help appreciated, thanks in advance

PhilipB
  • 329
  • 2
  • 16
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Aug 25 '16 at 12:58
  • 2
    you are probably trying to use the data before the asynchronous .getJSON() method finishes. – Cruiser Aug 25 '16 at 12:58
  • You should check if you JSON is valid with a JSON validator – Tim B Aug 25 '16 at 12:59
  • Try assigning your `long_short_data` inside the `.done` callback of your `$.getJSON()` function as `var jqxhr = $.getJSON( "/link/to/multiBarHorizontalData.json", function() { console.log( "success" ); }).done(function(data) { long_short_data = data; }) .fail(function() { console.log( "error" ); })` – David R Aug 25 '16 at 13:01
  • Thank you all for your answers, solved it trying @Leopard 's suggestion. – PhilipB Aug 25 '16 at 13:02

1 Answers1

2

$.getJSON doesn't return result as you are expecting. It returns data in callback. It should be

$.getJSON( "/link/to/multiBarHorizontalData.json", function(result) {
   long_short_data = result;
});
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40