Search code examples
javascriptjsonhighchartsjson-server

how to pull json data from a server/url and set equal to a variable?


I currently have a gauge chart from highcharts working with data that I directly input but now I am trying to transition to pulling the data (json fromat) from a server that is hosted through json-server --watch livePSAD.json --port 8000 this is the chart that I currently have https://jsfiddle.net/IzzyStrauch/9zuewk18/18/

series: [
      {
        name: "Speed",
        data: [85],
        tooltip: {
          valueSuffix: " RPM"
        }
      }
    ],

I am currently trying to figure out a way to set the data part of the series equal to http://localhost:8000/f0s which looks like this

[
  55
]

and have it live update every 3 seconds which I know I could possibly do through enablePolling: true but i cant event get it to just pull the static number of 55 from the url.

if (!chart.renderer.forExport) {
      setInterval(function () {
        var lg = 50;
        var hg = 120;
        var point = chart.series[0].points[0],
          axis = chart.yAxis[0];

        axis.update({
          plotBands: [
            {
              from: 0,
              to: lg,
              color: "red" // green
            },
            {
              from: lg,
              to: hg,
              color: "green" // yellow
            },
            {
              from: hg,
              to: 200,
              color: "red" // red
            }
          ]
        });
      }, 3000);
    }
  }

I then want to set the variable lg to http://localhost:8000/f0lg and hg to http://localhost:8000/f0hg which
lg looks like this

[
  30
]

hg looks like this

[
  70
]

and I want to have those also pull from that url every 3 seconds

Any thoughts as to how this might be possible?

Using the checked solution I now have all the variables entering and changing the chart but the tick marks are all wonky this is the new code https://jsfiddle.net/IzzyStrauch/1rx3tyjp/9/

(for some reason it works on jsfidle but not in my code where I am using it but it is exactly the same other than I have more charts on my page/code) Any thoughts on why this could be?


Solution

  • Check this demo that shows how to fetch a JSON data and initialize the chart: https://jsfiddle.net/BlackLabel/rdn4fyb7/

    fetch("https://api.npoint.io/6f74f002ed847e39cc3c")
      .then(response => response.json())
      .then(data => {
        //check how the fetched data looks like
        console.log(data)
    
        //create chart
        Highcharts.chart('container', {
    
          series: [{
                    type: 'column',
            data: data.data
          }]
        });
      });