0

How can i pass an array from a GET request like this:

[x, y], [x, y]...

Into the second part of this google visualization API call.

var data = google.visualization.arrayToDataTable([
['Initial', 'Second'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);

Currently i have the values pre-set, but i would like to pass them from a GET request. I have tried using PHP for this however failed using methods like this passing arrays as url parameter as i am not quite sure how to set the x value properly.

Below is the script i use to generate the chart:

  <script>
    google.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Initial', 'Second'],
        [8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);

      var options = {
        width: 420,
        height: 420,
        legend: 'none',
        trendlines: { 0: {} },
        colors: ['#FE2E2E'],
        hAxis: {
            textPosition: 'none',
            gridlines: {
                color: "#CCCCCC"
            },
            baselineColor: '#CCCCCC'
        },
        vAxis: {
            textPosition: 'none',
            gridlines: {
                color: "#CCCCCC"
            },
            baselineColor: '#CCCCCC'
        },
        enableInteractivity: false
      };

      var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
  </script>
3
  • The code which you have pasted is not a GET API call. I guess you want to parse the response from a GET call and set the data into the code. Am I correct? Commented Dec 26, 2014 at 4:33
  • If you will specify what chart you will use the data into. I can give you a working example. Commented Dec 26, 2014 at 4:40
  • Well looks like answer below was accepted and I don't have a scatter chart. :D Commented Dec 26, 2014 at 4:47

2 Answers 2

1

Once you have the response from the GET request:-

 var myArrayData = JSON.parse(responseData);

Now your data will be of the form

[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]

Then do:

myArrayData.unshift(['Initial', 'Second']);

Now you can try:

var data = google.visualization.arrayToDataTable(myArrayData);
Sign up to request clarification or add additional context in comments.

Comments

1

you could stringify it and pass as url encoded

var a = [[4,5], [6,7]];
var b = JSON.stringify(a); // "[[4,5], [6,7]]"
var x = encodeURIComponent(b); // "%5B%5B4%2C5%5D%2C%20%5B6%2C7%5D%5D"
var strArray = decodeURIComponent(x); // "[[4,5], [6,7]]"
var myArray = JSON.parse("[[4,5], [6,7]]"); // [[4,5], [6,7]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.