Php variable for javascript

Asked

Viewed 37 times

0

I am using Highchart to create charts, however I am not able to pass the value of data through a php variable:

series: [{
      name: 'Tendência',
      data: <?php echo $encodeValorTendencia; ?>
   },{
      name: 'Obtenção',
      data: <?php echo $encodeValorObtencao; ?>
}],

I’m already "bumping" the variables:

$valorTendencia[] = $value->Valor;
$encodeValorTendencia = json_encode($valorTendencia);

$valorObtencao[] = $value->ValorObtencao;
$encodeValorObtencao = json_encode($valorObtencao);

$dataHora[] = $value->DataHoraPrevisao;
$encodeDataHora = json_encode($dataHora);

The value of the variable $dataHora works, through this stretch:

xAxis: {
    categories: <?php echo $encodeDataHora; ?>
},

This way the graph appears with the date and time but the values of series do not.

  • Try to var_dump the variables outside of <script></script> and see if the values are OK.

  • I showed(var_dump) the $encodeValue variable and printed this: string '["2000","2000","2000","700","800","700","2000","2000","2000","2000","2000""]'

1 answer

1


To solve I used the constant JSON_NUMERIC_CHECK, of function json_encode, staying that way:

$valorTendencia[] = $value->Valor;
$encodeValorTendencia = json_encode($valorTendencia, JSON_NUMERIC_CHECK);

$valorObtencao[] = $value->ValorObtencao;
$encodeValorObtencao = json_encode($valorObtencao, JSON_NUMERIC_CHECK);

And switching to Javascript directly:

series: [{
   name: 'Tendência',
   data: <?php echo $encodeValorObtencao; ?>
},

The values despite being numbers, were as string ("value"): string '["2000","2000","2000","700","800","700","2000","2000","2000‌​","2000"]'

By using the constant JSON_NUMERIC_CHECK, values have become numerical since api requires that values passed in data: are numerical.

:string '[2000,2000,2000,700,800,700,2000,2000,2000,2000]'
  • Good +1, it would only be nice to explain the functioning of JSON_NUMERIC_CHECK, because you explained how you tidied up, but did not explain what caused the failure, if edit and explain will surely be useful for other users ;)

  • Perfect explanation. Congratulations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.