JQuery Chart by entering array values

0

So it's the folks next, I have 2 variables of type array that have been converted from php to javascript, so far everything is ok. I used alert to see if it showed and worked. What I intended was to save these 2 arrays within the variable date.

< script type = "text/javascript"
src = "https://www.gstatic.com/charts/loader.js" > < /script>

  <
  script type = "text/javascript" >

  <?php
$sql2 = "SELECT tag,contador FROM tags";
$result2 = $mysqli->query($sql2);

$tagparatudo = array();
$contadorparatudo = array();
while ($row2 = $result2->fetch_assoc())
  {
  $tagparatudo[] = $row2["tag"];
  $contadorparatudo[] = $row2["contador"];


  }

  $js_array = json_encode($tagparatudo);
  $array2 = json_encode($contadorparatudo);
  echo "var tags = ". $js_array. ";\n";
  echo "var contagem = ". $array2. ";\n";
  ?>

alert(contagem);
alert(tags);



// Load google charts
google.charts.load('current', {
  'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Something', 'Here'],
    ['Work', 5],
    ['Newthing', 5],
    ['Newthingz', 5]
  ]);
  // Optional; add a title and set the width and height of the chart
  var options = {
    'title': 'Tag Ranks',
    'width': 450,
    'height': 400
  };

  // Display the chart inside the <div> element with id="piechart"
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
} <
/script>
<div id="piechart"></div>

Will be created a google chart with values of the variable date and what I intended was something of the sort:

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Something', 'Here'],

um ciclo for{
        [array tags, array contagem]
}
  ]);
    
asked by anonymous 08.06.2017 / 16:37

2 answers

0

If your "alert" is working and displaying the data correctly, then it seems to me that what you need is to adjust the structure of the arrays you are mounting.

By its example, the variable "data" should be an array composed of arrays:

[
 ['Something', 'Here'],
 ['Work', 5],
 ['Newthing', 5],
 ['Newthingz', 5]
]

And what you're generating in PHP > JS are two different arrays:

['Item 1', 'Item 2', 'Item 3']
['Valor 1', 'Valor 2', 'Valor 3']
    
08.06.2017 / 16:49
0

Something that may be wrong is the following snippet:

 echo "var tags = ". $js_array. ";\n";
 echo "var contagem = ". $array2. ";\n";

Since json_encode returns a string, it is necessary to put quotes in this way:

echo "var tags = '". $js_array. "';\n";
echo "var contagem = '". $array2. "';\n";
    
08.06.2017 / 21:40