drypatrick
drypatrick

Reputation: 624

Plotting multiple series from JSON php import to Highcharts

because I'm pretty new to JS, I can't understand how to implement multiple data series into my code

Here is my php page that I use as data grabber:

getTrendData-TIMEREQUESTED-hms.php

<?php
    //Define possible Argument request
    $format = $_GET['format'];

    if($format=='json')    {
        header("Content-type: text/json");
    }

    //Define database credential
    $servername = "localhost";
    $username   = "test";
    $password   = "test";
    $dbname     = "test";
    try {
        //Open connection to mysql_db from defined Database credentials
        $connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
        $sql   = "select TIMEREQUESTED,TS FROM TIMEREQUESTED ORDER BY TS;";
        $result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
        //create an array
        $data = array();
        while($row = mysqli_fetch_assoc($result))    {
            $TIMEREQUESTED = strtotime($row['TIMEREQUESTED'])*1000;
            $TS = strtotime($row['TS'])*1000;
            $data[] = array($TS, $TIMEREQUESTED);
        }

        echo json_encode($data);
        //close the db connection
        mysqli_close($connection);
    }

    catch(PDOException $e)  {
        echo $e->getMessage();
    }

    ?>

Than I include in HighCharts with an Ajax call, that call himselfs each 2500 miliseconds,

getTrendData-TIMEREQUESTED-hms.php

[[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0],[1461242303000,26.25,0],[1461242835000,-2.5,0],[1461242869000,-2.5,0],[1461242991000,1.5,0],[1461243034000,3.14,0],[1461243374000,-14.22,0],[1461243456000,-11.92,0],[1461244995000,0,0],[1461245036000,-3.6,140],[1461245208000,-3,140],[1461245260000,3.56,140],[1461245312000,2.1,140],[1461245346000,2.1,140],[1461245411000,3.5,140],[1461245442000,3.5,140],[1461245479000,-1,140],[1461245757000,-0.8,140],[1461245809000,-0.69,140]]

TIMEREQUESTED-hms.html

function buildTIMEREQUESTED() {
  var chart;
  var dataSource = 'getTrendData-TIMEREQUESTED-hms.php?format=json';
  var ChartHeight = window.innerHeight;

  function requestData() {
    $.ajax({
      url: dataSource,
      success: function(points) {
        chart.series[0].setData(points, true);
        setTimeout(requestData, 2500);
      },
      cache: false
    });
  }
  $(document).ready(function() {
    //add our div for the chart
    $("#container").append("<div id=chart-laptime style='width:100%''></div>");
    chart = new Highcharts.Chart({
      chart: {
        height: ChartHeight,
        renderTo: 'chart-laptime',
        defaultSeriesType: 'line',
        events: {
          load: function() {
            requestData();
          }
        },
      },
      tooltip: {
        enabled: true,
        formatter: function() {
          s = (this.y / 1000);
          m = Math.floor(s / 60);
          h = Math.floor(m / 60);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          return '<span style="color:black">Time Zero - </span>' + [m, s].join(':');
        }
      },
      title: {
        text: 'TIMEREQUESTED'
      },
      subtitle: {
        text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
      },
      xAxis: {
        type: 'datetime',
        title: {
          text: 'RACE TIME'
        }
      },
      yAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
          millisecond: '%H:%M:%S',
        },
        //dateFormat: {"%H:%M:%S.%L"}
        title: {
          text: 'TIMEREQUESTED'
        }
      },
      series: [{
        name: 'TIMEREQUESTED',
        showInLegend: false,
        //tooltip: {type: 'datetime',},
        data: [],
      }]
    }); //end chart               
  }); //end document.ready
}

In that way I can get the single series proper displayed, but with the MySQL query I'm able to get more columns from the database, and parsing in each rows of the json file,(As is showed in the JSON file from php request, there is a third values for each array) but I'm not able to understand how to display multiple data series, with on the xAxis always the first column of the JSON file, and on the yAxis each time a different columns.

Could you please give me some suggestions on how to display multi series on the same graph? It would be so much appreciated,

Best regards.

Upvotes: 0

Views: 1283

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 912

var dataForTwoSeries = [[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0]]; //your data, just took 3 elements. Should work for any number of elements.
var seriesOne = [];
var seriesTwo = [];
$.each(dataForTwoSeries, function(index, dataPoints){
   var seriesOneDataPoint = [dataPoints[0], dataPoints[1]];
   var seriesTwoDataPoint = [dataPoints[0], dataPoints[2]];

   seriesOne.push(seriesOneDataPoint);
   seriesTwo.push(seriesTwoDataPoint);
});

And then you'll have to create 2 series in your chart object like

series: [{
    name: 'seriesName1',
    showInLegend: false,
    data: [],
},{
    name: 'seriesName2',
    showInLegend: false,
    data: [],
}]

And in your requestData method, set the data for both like

chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

EDIT : After your updated code, these are the changes you further need to make.

$.ajax({url: dataSource, success: function(dataForTwoSeries) //dataForTwoSeries is the data you get from the request 
  {
  //var dataForTwoSeries = []; you don't need this.
  var seriesOne = []; //these two don't have to be global.
  var seriesTwo = [];
  $.each(dataForTwoSeries, function(index, dataPoints){

    var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
    var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];

    seriesOne.push(seriesOneDataPoint);
    seriesTwo.push(seriesTwoDataPoint);
  }); // draw chart after iteration and not during each interation
    chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
    chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

    setTimeout(requestData, 2500);

  },
  cache: false
  });

Upvotes: 1

drypatrick
drypatrick

Reputation: 624

I've update the code and now is free from syntax error, but I have no data displayed. I'm going to put some windows.allert() tu understand where the data flow is broken.

Here's the updated code:

<!DOCTYPE html>
<html>
<head>
    <title>Strategy - Time Zero</title>
    <script src="js/jquery/jquery-1.12.3.js"></script>
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="js/Highcharts/Highcharts-4.2.3/highcharts.js"></script>
    <script src="js/Highcharts/Highcharts-4.2.3/modules/exporting.js"></script>
    <script>

  var chart;
  var dataSource = 'getTrendData-TimeZero.php?format=json';
  var ChartHeight = window.innerHeight;
  var dataForTwoSeries = [];
  var seriesOne = [];
  var seriesTwo = [];

  function requestData() {

    $.ajax({url: dataSource, success: function(dataPoints) 
      {
      $.each(dataForTwoSeries, function(index, dataPoints){

        var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
        var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];
        window.alert(seriesOneDataPoint)

        seriesOne.push(seriesOneDataPoint);
        seriesTwo.push(seriesTwoDataPoint);

        chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
        chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

        setTimeout(requestData, 2500);
      });
      },
      cache: false
      });


  }
  $(document).ready(function() {
    //add our div for the chart
    $("#container").append("<div id=chart-TimeZero style='width:100%''></div>");
    //StockChart
    //Chart
    chart = new Highcharts.Chart({
      chart: {
        height: ChartHeight,
        renderTo: 'chart-TimeZero',
        defaultSeriesType: 'line',
        events: {
          load: function() {
            requestData();
          }
        },
      },
      tooltip: {
        enabled: true,
        formatter: function() {
          if (this.y < 0) 
          {
          h = Math.ceil(this.y / 3600);
          m = Math.ceil(this.y / 60);
          s = Math.ceil(this.y % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "-0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          else
          {
          h = Math.floor(this.y / 3600);
          m = Math.floor(this.y / 60);
          s = Math.floor(this.y % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          return '<span style="color:black">Time Zero</span> ' + [h, m, s].join(':');
        }
      },
      title: {
        text: 'TIME ZERO'
      },
      subtitle: {
        text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
      },
      xAxis: {
        type: 'datetime',
        title: {text: 'DAY TIME'}
      },
          yAxis: {
        title: {text: 'TIME ZERO'},
        labels: {                
        formatter: function() {
          if (this.value < 0) 
          {
          h = Math.ceil(this.value / 3600);
          m = Math.ceil(this.value / 60);
          s = Math.ceil(this.value % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "-0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          else
          {
          h = Math.floor(this.value / 3600);
          m = Math.floor(this.value / 60);
          s = Math.floor(this.value % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          return [h, m, s].join(':');
        }
        }
    },
series: [{
    name: 'seriesName1',
    showInLegend: true,
    data: [],
},{
    name: 'seriesName2',
    showInLegend: true,
    data: [],
}]
    }); //end chart       
  }); //end document.ready

</script>
</head>
<body>
    <div id="container"></div>
</body>
</html>

Upvotes: 0

Related Questions