Search code examples
javascriptdom-events

JavaScript Variable and passing data issues


I have an issue in that the $.getJSON segment of code works fine and produces a variable called 'zippy'. I need to access 'zippy' under 'series: data' further down in the code.

I have tried a number of things unfortunately I can't make it work. The easiest would be way to 'return data' $.getJSON(jsonUrl,function(zippy) out of the function(zippy) call but I'm lost as to how to make that data available.

$(function() {
    $(document).ready(function() {
        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        console.log("+++++++++++++++++++++++++++++++++++++");
        var jsonUrl = "http://www.someurl.com/thing.php?callback=?";

        $.getJSON(jsonUrl, function(zippy) {
            for(i = 0; i < zippy.cpmdata.length; i++) {
                console.log("TIMESTAMP: " + zippy.cpmdata[i].timestamp + " AFTER: ");


                zippy.cpmdata[i].timestamp = Date.parse(zippy.cpmdata[i].timestamp).getTime() / 1000;
                //var unixtime  Date.parse(temptime).getTime()/1000

                console.log(" TESST " + zippy.cpmdata[i].timestamp + " \r\n");

            }
        });
        console.log("+++++++++++++++++++++++++++++++++++++");

        var chart;
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'spline',
                marginRight: 10,
                events: {
                    load: function() {

                        // set up the updating of the chart each second
                        var series = this.series[0];
                        setInterval(function() {
                            var x = (new Date()).getTime(), // current time
                                y = Math.random();
                            series.addPoint([x, y], true, true);
                        }, 1000);
                    }
                }
            },
            series: [{
                name: 'Random data',
                data: (function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    console.log("++NEED ACCESS HERE FOR ZIPPY++");
                    console.log(" =============== \r\n");
                    console.log(" FINAL " + zippy.cpmdata[5].timestamp + " \r\n");
                    return data;
                })()
            }]



        }

Solution

  • Your problem is that getJSON is asynchronous. What's happening in your code is this:

    1. document.ready is triggered
    2. getJSON is called and registers a callback "function(zippy)" note that getJSON returns immediately without executing the callback
    3. You try to draw a chart using HighCharts

      ... several hundred milliseconds later

    4. The browser makes the JSON request

      ... several hundred milliseconds later

    5. The JSON request returns with data and triggers the callback to "function(zippy)"

    6. "function(zippy)" is executed

    So you see. The problem is not how "function(zippy)" is executed but when it is executed. As such, you cannot execute code that wants to use the return value of the JSON request outside of the callback function. (Actually you can but we'll ignore polling with setTimeout or using synchronous ajax for now)

    The solution is to move all the code that you want to run later on inside the callback function:

    $.getJSON(jsonUrl, function(zippy) {
            for(i = 0; i < zippy.cpmdata.length; i++) {
                console.log("TIMESTAMP: " + zippy.cpmdata[i].timestamp + " AFTER: ");
    
    
                zippy.cpmdata[i].timestamp = Date.parse(zippy.cpmdata[i].timestamp).getTime() / 1000;
                //var unixtime  Date.parse(temptime).getTime()/1000
    
                console.log(" TESST " + zippy.cpmdata[i].timestamp + " \r\n");
    
            }
    
            var chart;
            chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'spline',
                marginRight: 10,
                events: {
                    load: function() {
    
                        // set up the updating of the chart each second
                        var series = this.series[0];
                        setInterval(function() {
                            var x = (new Date()).getTime(), // current time
                                y = Math.random();
                            series.addPoint([x, y], true, true);
                        }, 1000);
                    }
                }
            },
            series: [{
                name: 'Random data',
                data: (function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;
    
                    console.log(" FINAL " + zippy.cpmdata[5].timestamp + " \r\n");
                    return data;
                })()
            }]
        });