Graphics in JS, error inserting DB data

3

I have a huge problem at hand. I have some graphs in js , where I need the data entered in them to come from the database.

But as js is built, I can not find any way to allocate the database data in the charts. However, it already assigns the database data to other variables js , to make it easier.

I'm still struggling. I hope someone can help me: /

ATTENTION: It is not simply to replace the variables one by one, but to do so in a way that the process is automatic, and whenever you add or change a value in the database, automatically. I thought about cycling while or for , but I do not know how!

Here is how variables are assigned in JS of data coming from BD :

var row=[];
<?php
$graph=$conn->query("SELECT * FROM lucro")or die("erro");
if($graph->num_rows>0){
    ?>
    var num=<?php echo $graph->num_rows;?>;
      for(var i=0;i<=<?php echo $graph->num_rows; ?>;i++){
        row[i]=[];
      }
    <?php
    $i=0;
    while($row=$graph->fetch_assoc() and $i<=$graph->num_rows){
      $data=date('M',strtotime($row['data']));
      ?>
        row[0][<?php echo $i+1; ?>]="<?php echo $data; ?>";
        row[<?php echo $i; ?>][0]=<?php echo $row['lucro'];?>;

      <?php
    $i++;
    }
}?>
var i=0;

And here we have the code of the graph where I want to exchange for these variables:

//GRAFICO do lucro p/ANO
 var myConfig = {
  type: "bar",
  plotarea: {
    adjustLayout: true
  },
  scaleX: {
    label: {
      text: "em MILHÕES"
    },

  //AQUI EM BAIXO É ONDE QUERO INSERIR AS VARIAVEIS JS COM OS DADOS DA BD:
    labels: ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug"]
  },
  series: [{

  //AQUI EM BAIXO É ONDE QUERO INSERIR AS VARIAVEIS JS COM OS DADOS DA BD:
    values: [20, 40, 25, 50, 15, 45, 33, 34]
  }]
};

zingchart.render({
  id: 'myChart',
  data: myConfig,
  height: "80%",
  width: "100%"
});
    
asked by anonymous 18.06.2016 / 14:47

1 answer

2

You can do this:

$labelsJS = array();
$valsJS = array();

while($row=$graph->fetch_assoc() and $i<=$graph->num_rows){
  $data=date('M',strtotime($row['data']));
  ?>
    row[0][<?php echo $i+1; ?>]="<?php echo $data; ?>";
    row[<?php echo $i; ?>][0]=<?php echo $row['lucro'];?>;

    $labelsJS[] = $data;
    $valsJS[] = $row['lucro'];
  <?php
   $i++;
}

$labelsJS = json_encode($labelsJS);
$valsJS = json_encode($valsJS);

Then in js do, I suppose here already see the variable $labelsJS and $datas declared and with the values entered above:

var labels = <?= "JSON.parse('" .$labelsJS. "');"; ?>
var values = <?= "JSON.parse('" .$valsJS. "');"; ?>

//GRAFICO do lucro p/ANO
var myConfig = {
  type: "bar",
  plotarea: {
    adjustLayout: true
  },
  scaleX: {
    label: {
      text: "em MILHÕES"
    },
    labels: labels
  },
  series: [{
    values: values
  }]
};
    
18.06.2016 / 22:27