ThatGuy343
ThatGuy343

Reputation: 2424

Pass array from URL to javascript

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>

Upvotes: 0

Views: 67

Answers (2)

Jay
Jay

Reputation: 1478

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);

Upvotes: 1

Todd
Todd

Reputation: 5454

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]]

Upvotes: 1

Related Questions