0

According to highcharts documentation. It is not possible to use the jQuery.getJSON() function on JSON files outside of your own domain. It is, however, possible to use JSONP. Cross-domain data. This is their example: Source: https://www.highcharts.com/docs/working-with-data/getting-data-across-domains-jsonp

The serverside php file:

<?php
    header("content-type: application/json"); 

    $array = array(7,4,2,8,4,1,9,3,2,16,7,12);

    echo $_GET['callback']. '('. json_encode($array) . ')';
?>

The JavaScript calling the callback function using jQuery.

$(document).ready(function() {
    var options = {
        chart: {
            renderTo: 'container',
            type: 'spline'
        },
        series: [{}]
    };

    var url =  "http://url-to-your-remote-server/jsonp.php?callback=?";
    $.getJSON(url,  function(data) {
        options.series[0].data = data;
        var chart = new Highcharts.Chart(options);
    });
});

How would I do the same with a live data JSON API call, with a setTimeout request on for instance 30 seconds?

JSON LIVE DATA URL: https://canvasjs.com/services/data/datapoints.php?xstart=1&ystart=10&length=10&type=json

I have searched this answer for 2 days, I can only find this example, it seems to be a different approach using jQuery ajax() function creating random data, not from an external URL:

https://www.highcharts.com/docs/working-with-data/live-data

Modified code with own api: http://marialaustsen.com/apii.json

<html>

<head>
    <title>Team memberttttts received and sent eCards</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
<script>
        function visitorData (data) {
   $('#container').highcharts({
    chart: {
        type: 'column'
    },
    title: {
        text: 'Average Visitors'
    },
    xAxis: {
                    type: 'datetime',
                    labels: {
                        formatter: function () {
                            return Highcharts.dateFormat('%b %e. %Y', this.value, 1);
                        }
                    }
                },
    yAxis: {
        title: {
            text: 'Number of visitors'
        }
    },
    series: data,
  });
}
$(document).ready(function() {
 $.ajax({
    url: 'http://marialaustsen.com/apii.json?callback=?',
    type: 'GET',
    async: true,
    dataType: "json",
    success: function (data) {
        visitorData(data);
    }
  });
 });
    </script>
</head>

<body>
    <div id="container" style="width: 75%; height: 500px; margin: 0 auto"></div>


</body>

</html>

I removed the header in the api file, and replaced curly brackets with square brackets:
[ ["Timestamp":"1262304000","Sent ecards":"843","Sent recognition":"736","Received ecards":"21","Received recognition":"4311"]
] I get this error in the console: marialaustsen.com/apii.json?callback=jQuery321017746123134921787_1514030331673&_=1514030331674:2 Uncaught SyntaxError: Unexpected token :

As I have to be able to automatically update my api request, I need to find a way to fetch or output my json api correctly for highcharts. I read somewhere highcharts only reads timestamp in milliseconds, but it seems like the syntax is incorrect and not the data format.

marialaustsen
  • 105
  • 3
  • 14

1 Answers1

0

This demo might be helpful for you: http://jsfiddle.net/kkulig/dv74ze6n/

I uses promises to handle asynchronous getJSON requests. The solution from this topic allows me to perform requests to another domain: Changing getJSON to JSONP

Full code:

function getData() {
  return new Promise((resolve, reject) => {
    $.getJSON('https://canvasjs.com/services/data/datapoints.php?xstart=1&ystart=10&length=10&type=json&callback=?', function(recData) {
      resolve(recData);
    });
  });
}

(async() => {
  Highcharts.chart('container', {

        chart: {
        events: {
        load: function() {
            var series = this.series[0];
            setInterval(async function() {
            var data = await getData();
            series.setData(data);
          }, 2000);
        }
      }
    },

    series: [{
      data: await getData()
    }]

  });
})();

Live demo: http://jsfiddle.net/kkulig/dv74ze6n/

Kamil Kulig
  • 5,756
  • 1
  • 8
  • 12
  • Thanks for the help. I am still very confused about how Highcharts work with external json data, most examples online from Highcharts own sources don't give many complex or external api examples. This data URL is in this format: ?([[1,6],[2,5],[3,8],[4,12],[5,7],[6,7],[7,10],[8,9],[9,13],[10,10]]); I have exported a JSON file from my database in this format: [ {"Timestamp":"1262304000","Sent ecards":"843","Sent recognition":"736","Received ecards":"21","Received recognition":"4311"}] http://marialaustsen.com/api.json How would I fetch this data into highcharts via an URL? Many thanks! – marialaustsen Dec 22 '17 at 18:10
  • This docs page should clarify which data format Highcharts/Highstock accepts: https://www.highcharts.com/docs/chart-concepts/series (*THE DATA IN A SERIES* paragraph). Highstock always use **datetime** type of the x axis so this article should also be helpful: https://www.highcharts.com/docs/chart-concepts/axes (*DATETIME* paragraph). You can either prepare your data so that it's in format acceptable for Highcharts or use **keys** property: https://api.highcharts.com/highcharts/plotOptions.series.keys – Kamil Kulig Dec 26 '17 at 07:10