PHP data in Javascript document

Asked

Viewed 47 times

0

Good afternoon.

I have the following code in PHP, rather simple:

<?
    include("conexao.php");
    $sql = mysql_query("select top 1 * from grafico_tb order by data_referencia desc");
    $dados = mysql_fetch_assoc($sql);

    $dados['perc1'];
    $dados['perc2'];
?>

And I have the following javascript code: grafico.js

initSparklineCharts: function() {
    if (!jQuery().sparkline) {
            return;
        }
    $("#sparkline_bar").sparkline([8, 9], {
                type: 'bar',
                width: '100',
                barWidth: 5,
                height: '55',
                barColor: '#f36a5b',
                negBarColor: '#e02222'
            });
};

Instead of "8" and "9", I intended to play the variables created within the document .php. I’ve tried creating this same chart inside the tag <script></script> in a .php as follows:

initSparklineCharts: function() {
    if (!jQuery().sparkline) {
            return;
        }
    $("#sparkline_bar").sparkline([<? $dados['perc1'].','.$dados['perc2']?>], {
                type: 'bar',
                width: '100',
                barWidth: 5,
                height: '55',
                barColor: '#f36a5b',
                negBarColor: '#e02222'
            });
};

And also with the echo in front of the variables but it didn’t work. Some solution?

The graph works with the values "8" and "9" without being variables and the variables in php also work.

Thank you!

3 answers

0

test this here in place of your php

<?PHP print("$dados[perc1] , $dados[perc2]"); ?>

will stay like this

initSparklineCharts: function() {
    if (!jQuery().sparkline) {
            return;
        }
    $("#sparkline_bar").sparkline([<?PHP print("$dados[perc1] , $dados[perc2]"); ?>], {
                type: 'bar',
                width: '100',
                barWidth: 5,
                height: '55',
                barColor: '#f36a5b',
                negBarColor: '#e02222'
            });
};

0

If you want to play PHP inside a JS file. You will create a PHP file and put as output APLICATION/JAVASCRIPT in a HEADER. It looks like this: grafico.php

0

John I use a similar graphics plugin, but the application is the same in your template also follows my example:

[<?php
 $sql = "SELECT...";
 $result = $conn->query($sql);
 if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
        echo $row['data'].",";
  }
 ?>]

Browser other questions tagged

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