combinar Javascript HTML PHP

I am doing this little project. Everything seems working , but I want to make even better. I have code

-Part1 -takes date from database and converts to JSON

$sth = mysql_query("select Value, Stats from table");
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Stats', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number')
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Stats']); 
$temp[] = array('v' => (int) $r['Value']); 
$rows[] = array('c' => $temp);
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);

-Part 2 Draws Google Bar chart and shows it on page

<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);   
   var options = {
    legend: {position: 'none'},
           bar: {groupWidth: "85%"},
    hAxis: {viewWindowMode: 'explicit'},
  }                        };                  
  var chart = new google.visualization.BarChart(document.getElementById('charts_div'));
  chart.draw(data, options);
<div class='data' id="charts_div" style="width:100%; height:200px"></div>

-My Qyestion

How to convert (combine) Part2 code to php. I tried echo around lines, but unsuccesfully

I want to assign Part2 as Php variable $Graph1 and then echo $graph1 on page, because It works better with my other code, so its consistent.

Entonces me gustaría algo como:

$graph = "<div class='data'><ul>" . $graph1 . "</ul></div>
echo $graph

preguntado el 05 de febrero de 14 a las 17:02

Here's a clean way to deliver data to the client ejecutable -

1 Respuestas

Why don't you just add it after the ?> ?

In PHP you can include HTML like this

// My PHP Code
echo "test";
<H1>My Title in HTML</H1>
<script> ... </script>
echo "test2";

You can also include PHP into HTML

<script> var a = "<?php echo $somevariable; ?>"</script>

You can also wrap your HTML code into a PHP variable care about the ". You will need to escape it or us single quote instead:

$myHTML = "<script> window.location=\"\";</script>";
$myHTML = "<script> window.location= '' ;</script>";
echo $myHTML;

Respondido 05 Feb 14, 17:02

Btw, I wouldn't recommend to merge HTML and PHP. There are several technique (like MVC model) in order to separate actions from visual. But this is only my opinion. - yves lange

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.