Drew
Drew

Reputation: 21

JScript JSON Array access

I have a JSON array stored in a file data.json - I used the code that was recommended here for a similar problem, explain why when I try to access the array later in the program it tells me it is undefined.

    var chartData = (function () {
                var chartData = null;
                $.ajax({
                    'async': false,
                    'global': false,
                    'url': "data.json",
                    'dataType': "json",
                    'success': function (data) {
                        chartData = data;
                    }
             });
             return chartData;
        })();

Help appreciated!

Edit; For accessing, I'm using the array as a series in dojo-chart: http://dojotoolkit.org/grids-charts

After I attempt to initialize var chartData, the only other point I use it is in:

    chart.addSeries("Name",chartData);

Edit #2; In case it matters the data.json file is formatted like:

    [#, #, #, ... , #]

Upvotes: 0

Views: 263

Answers (2)

Arend
Arend

Reputation: 3761

Perhaps because it was not successful? I found it very useful to debug using console.log (firebug, or most modern web developer panels in chrome or ie support it)

you can try this piece of code to debug it.

var chartData = (function () {
            var chartData = null;
            $.ajax({
                'async': false,
                'global': false,
                'url': "data.json",
                'dataType': "json",
                'success': function (data) {
                    console.log('success');
                    console.log(data);
                    chartData = data;
                }
                error: function (data) { console.log('error'); console.log(data); },
         });
         return chartData;
})();

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816442

I guess it should work somehow as you set async: false. But better is to use it asynchronously:

function handler(chartData) {
    // all the code here that deals with chartData
}

$.ajax({
    url: "data.json",
    dataType: "json",
    success: handler
});

Upvotes: 1

Related Questions