3

I'm new to javascript so please forgive me. I am trying to make a line chart (with 4 lines) which get updated every hour. The information will be found in a JSON file however I am unsure how to write it. Previously I have tried to use data.addColumn() and data.addRows() but I couldn't find a way to connec that with a JSON file. Say if you were to make an example, please show the number of sales of four different items

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

        google.charts.load('current', {
        packages: ['corechart']
        }).then(function () {

        var options = {
            hAxis: {
            title: 'Time'
            },
            vAxis: {
            title: 'Sales'
            },
            title: 'Today',
            height: 600
        };

        var chart = new google.visualization.LineChart(document.getElementById('dagens'));

        var jsonData = $.ajax({
            url: 'getData.php',
            dataType: 'json',
        })

            drawChart(jsonData);

        }).done(drawChart);


        function drawChart(jsonData) {
            var data = new google.visualization.DataTable(jsonData);
            chart.draw(data, options);
        }

    </script>

In the getData.php file this is written:

$string = file_get_contents("sampleData.json");
echo $string;

I wish to use google's chart system if possible. Many thanks in advance.

Edit: JSON file:

{
  cols: [{label: 'Time', type: 'number'},
         {label: 'Sales 1', type: 'number'},
         {label: 'Sales 2', type: 'number'},
     {label: 'Sales 3', type: 'number'},
     {label: 'Sales 4', type: 'number'}
  ],
  rows: [
     {c:[{v: 0}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 1}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 2}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 3}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 4}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 5}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 6}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 7}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 8}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 9}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 10}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 11}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 12}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 13}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 14}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 15}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 16}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 17}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 18}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 19}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 20}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 21}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 22}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]},
     {c:[{v: 23}, {v: 1000}, {v: 1000}, {v: 1000}, {v: 1000}]}
  ]
}
2
  • 1
    can you also post data for jsonData Commented Feb 6, 2020 at 13:44
  • I have added the JSON file now Commented Feb 7, 2020 at 8:36

1 Answer 1

3

in order to create a google data table, directly from json, as follows...

var data = new google.visualization.DataTable(jsonData);

the json data must be in a very specific format, found here.

as for the format of the data for a specific chart,
each has a specific format, the data format for line chart can be found here.

the first column in the data table represents the x-axis,
it can be of any type (date, number, string, etc...).

the following columns should all be numbers,
which represent each series in the chart, or line to be drawn.

so an example of the json needed to draw a line chart,
with a date on the x-axis,
and four lines is as follows...

var jsonData = {
  "cols": [
    {"label": "Date", "type": "date"},
    {"label": "Sales A", "type": "number"},
    {"label": "Sales B", "type": "number"},
    {"label": "Sales C", "type": "number"},
    {"label": "Sales D", "type": "number"}
  ],
  "rows": [
    {"c":[{"v": "Date(2019, 10, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]},
    {"c":[{"v": "Date(2019, 11, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]},
    {"c":[{"v": "Date(2020, 0, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]},
    {"c":[{"v": "Date(2020, 1, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]}
  ]
};

when using ajax to get the json data,
do not use --> async: false -- this option has been deprecated.

instead use the done promise method, which will have the data as an argument.

$.ajax({
  url: "getData.php",
  dataType: "json",
}).done(function (jsonData) {  // <-- json data argument
});

see following working snippet,
here, I use the fail promise method to hard-code the data,
since your php page cannot be reached from this site.
on your server, it should work without the fail method...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {

  var options = {
    hAxis: {
      title: 'Time'
    },
    vAxis: {
      title: 'Sales'
    },
    title: 'Today',
    height: 600
  };

  var chart = new google.visualization.LineChart(document.getElementById('today'));

  $.ajax({
    url: 'getData.php',
    dataType: 'json',
  }).fail(function () {

    var jsonData = {
      "cols": [
        {"label": "Date", "type": "date"},
        {"label": "Sales A", "type": "number"},
        {"label": "Sales B", "type": "number"},
        {"label": "Sales C", "type": "number"},
        {"label": "Sales D", "type": "number"}
      ],
      "rows": [
        {"c":[{"v": "Date(2019, 10, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]},
        {"c":[{"v": "Date(2019, 11, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]},
        {"c":[{"v": "Date(2020, 0, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]},
        {"c":[{"v": "Date(2020, 1, 1)"}, {"v": 1000}, {"v": 2000}, {"v": 3000}, {"v": 4000}]}
      ]
    };

    drawChart(jsonData);

  }).done(drawChart);


  function drawChart(jsonData) {
    var data = new google.visualization.DataTable(jsonData);
    chart.draw(data, options);
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="today"></div>


EDIT

there is a problem with the ajax call.
change from...

    var jsonData = $.ajax({
        url: 'getData.php',
        dataType: 'json',
    })

        drawChart(jsonData);

    }).done(drawChart);

change to...

    $.ajax({
        url: 'getData.php',
        dataType: 'json',
    }).done(drawChart);

also, it appears you're missing the closing bracket to the load statement promise.
try this code...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {

  var options = {
    hAxis: {
      title: 'Time'
    },
    vAxis: {
      title: 'Sales'
    },
    title: 'Today',
    height: 600
  };

  var chart = new google.visualization.LineChart(document.getElementById('dagens'));

  $.ajax({
    url: 'getData.php',
    dataType: 'json',
  }).done(drawChart);


  function drawChart(jsonData) {
    var data = new google.visualization.DataTable(jsonData);
    chart.draw(data, options);
  }

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

12 Comments

Thanks this helped a lot. However, I am still unsure about one thing. What you have written as the fail function, is this only going to display if my the JSON file fails to be read? I am still unable to retrieve any data from the JSON file and I believe I have written it correctly.
Alright, edited so my current version is displayed. Edit: Also, your example showed me how to check the values at specific dates. I wish to see the graph of sales every hour.
as for hours, you can use numbers as in your example, or you can add hours to the dates in my example --> "Date(2020, 0, 1, 1)" -- or you can even use another type --> "timeofday" -- which is an array with 3 numbers for hour, minute, second --> [1, 0, 0]
It still doesn't work. I don't know if it matters but I am trying to run the code in my web browser and also from an http-server. All the files are currently located on my desktop.
Well, seems like there are two errors. "Access to XMLHttpRequest at file:///C:/.../getData.php from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." AND "GET file:///C:/.../getData.php net::ERR_FAILED"
|

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.