1

I have an AJAX response that's delivering some data to a Javascript page. I'm taking the original response and formatting it into individual arrays.

Array 1 is

["option1","option2","option3"]

Array 2 is

[ "["0.0","2.0","1.0","1.0","3.0"]","["1.0","2.0","11.0","11.0","12.0"]","["0.0","0.3","2.0","0.0","6.0"" ]

Array 3 is

["2019-01-07 05:00:00","2019-01-07 05:30:00","2019-01-07 06:00:00","2019-01-07 06:00:00","2019-01-07 06:30:00"]

I want to try and generate a chartjs line chart using this data with the caveat that there will often be more options in the first 2 arrays.

Array 3 on the X-Axis, Array 2 on the Y-Axis and Array 1 as the items in the legend and in the chart.

Can anyone suggest a starting point for this as I seem to be getting to a point where I can output the data but can't make the chart dynamic enough to get the data in?

There is an option of the first 2 arrays being combined in the JSON to form;

{
  "Labels": "option1",
  "Array": "["0.0","2.0","1.0","1.0","3.0"]"
},
{
  "Labels": "option2",
  "Array": "["1.0","2.0","11.0","11.0","12.0"]"
},
{
  "Labels": "option3",
  "Array": "["0.0","0.3","2.0","0.0","6.0"]"
}

There's no issue generating the charts if I know how many items will be in the original array but I need this to be dynamic - Although the date range will be static.

EDIT

Here's the Script I'm using to call the data at the moment;

function drawChart() {

  var jsonData = $.ajax({
    url: 'includes/private/test6.php',
    dataType: 'json',
  }).done(function (results) {

    var label = []; 
    var array = [];

    results.forEach(function(data) {
      label.push(data.Label);
      array.push(data.Array);
      //console.log(data.Label);
    });

    var temp = {
      labels : label,
      datasets : [{
                    data: array
      }]
    };

    var ctx = document.getElementById("chart").getContext("2d");
    var chart_vehicle = new Chart(ctx,temp);    
  });
}

drawChart();

console.log(data.Label) returns nothing in this example - My previous version was;

$.ajax({
  type: 'GET',
  url: 'includes/private/test6.php',
  dataType: 'json',     
  success: function (data) {
      var label = [];
      var array = [];
    for(var i in data) {
    label[i] = data[i].Labels; 
    array[i] = data[i].Array; 
}

// used to correctly format the JSON
var names = label.slice(0, -1);  
var data = array.slice(0, -1); 

// Used to flip the array and return the first entry - Dates will always be the last thing returned.
var dates = JSON.parse(array.reverse(array)[0]); 

console.log(data);
console.log(names);
console.log(dates);

This correctly returns the data but I still can't get the data into a chart dynamically.

Another EDIT

I've made a few more changes and done a lot more reading. Here's my fiddle containing my JSON response. No chart is generated but I'm pretty sure the data should be correct!

https://jsfiddle.net/s04nye6h/7/

2
  • you wrote "Label" in your new code. but in your previous you wrote with "s" ->Lables . i think because that the console.log show nothing Commented Sep 20, 2018 at 17:24
  • Thanks for that... I still can't get the data to output correctly though. jsfiddle.net/s04nye6h/7 Commented Sep 21, 2018 at 10:48

1 Answer 1

1

Ok. So I had to move your code upside down.

The JSON format and json type was wrong

As per ChartJs this example correct format for generating chart is this

var config = {
        type: 'line',
        data: {
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [{
                label: 'dataset - big points',
                data: [
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor()
                ],
                backgroundColor: window.chartColors.red,
                borderColor: window.chartColors.red,
                fill: false,
                borderDash: [5, 5],
                pointRadius: 15,
                pointHoverRadius: 10,
            }, {
                label: 'dataset - individual point sizes',
                data: [
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor(),
                    randomScalingFactor()
                ],
                backgroundColor: window.chartColors.blue,
                borderColor: window.chartColors.blue,
                fill: false,
                borderDash: [5, 5],
                pointRadius: [2, 4, 6, 18, 0, 12, 20],
            },]
        }

    };

    window.onload = function() {
        var ctx = document.getElementById('canvas').getContext('2d');
        window.myLine = new Chart(ctx, config);
    };

issue 1: What you were trying is this

var config = {
      type: 'line',
      labels: XXdates,
      datasets: []
    }

Notice the missing data attr

issue 2: Data format has to be in Array of Number

eg: [  1,2,3,4,5]

but your data returns like this

"[ "1", "2" ,"0" ]"

Solution : Working Code after resolving above points

function drawChart() {

  var jsonData = $.ajax({
    url: 'https://api.myjson.com/bins/11poyc',
    dataType: 'json',
  }).done(function(results) {

    var label = [];
    var output = [];

    results.forEach(function(data) {
      label.push(data.Labels);
      output.push(data.Array);
    });

    var XXnames = label.slice(0, -1);
    var XXdata = output.slice(0, -1);

    var XXdates = JSON.parse(output.reverse(output)[0]);


        var data = {
            labels: XXdates,
        datasets: []
    }

    XXnames.forEach(function(XXa, i) {

        console.log(JSON.parse(XXdata[i]).map(Number));

      data.datasets.push({
        label: XXa,
        fillColor: 'rgba(220,220,220,0.2)',
        strokeColor: 'rgba(220,220,220,1)',
        pointColor: 'rgba(220,220,220,1)',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(220,220,220,1)',
        data: JSON.parse(XXdata[i]).map(Number)
      });
    });

        var config = {
      type: 'line',
      data : data
    }

    var ctx = document.getElementById("chart").getContext("2d");
    var chart = new Chart(ctx, config);
  });
}

drawChart();

Working Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

OMG! Thank you so much for looking at this. I'm actually quite happy with how close I got. Knowing how to identify the problem is where my knowledge falls down!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.