I have created a PHP connection to my database and made the following query:
$taxRates = array();
while($row = mysql_fetch_assoc($result)) {
$taxRates[] = $row['mar_tax_rate'];
}
I then encoded the result as follows:
$jsonobj = json_encode($taxRates, JSON_NUMERIC_CHECK);
echo "This is jsonobj:<br>" . $jsonobj . "<br>";
Which returns:
This is jsonobj:
[0,0.35,0.35,0.35,0.35,0.35,0.35,0.35,0.35]
The problem that I am having is this. When I try to echo these results into JS, my result is coming back empty (as far as I can see) — not an empty array, just nothing. This is how I am trying to feed the result into JS:
data:[<?php echo $jsonobj; ?>]
Which returns:
data:
I have tried to alert the PHP variable using
alert("<?php echo $jsonobj; ?>");
which produces an alert, but is also empty.
Any thoughts?
Here is the full code:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script type="text/javascript" src="includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="includes/js/highcharts.2.3.2.js"></script>
<script type="text/javascript" src="includes/js/highstock.src.js"></script>
<script type="text/javascript">
$(document).ready(function() {
drawChart();
});
function drawChart() {
alert("<?php echo join($jsonobj); ?>");
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
type: 'column',
},
credits: {
enabled: false
},
series: [{
data:[<?php echo $jsonobj; ?>]
}]
});
};
</script>
</head>
<body>
<button style="height:100px; width:300px;" onclick="drawChart();">Redraw the Chart</button><br />
<div id="chart"></div>
<?php
$link = mysql_connect('url', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//mysql_close($link);
$db_selected = mysql_select_db('bloch',$link);
if (!$db_selected) {
die ('Can\'t use Bloch Database : ' . mysql_error());
}
$result = mysql_query('SELECT mar_tax_rate from bloch.bloch_deficit');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$taxRates = array();
while($row = mysql_fetch_assoc($result)) {
$taxRates[] = $row['mar_tax_rate'];
}
$jsonobj = json_encode($taxRates, JSON_NUMERIC_CHECK);
echo "This is jsonobj:<br>" . $jsonobj . "<br>";
?>
</body>
</html>
Your variable isn’t being defined before you try and put it in to your HTML. Create the variable with what you need before your HTML in order to get it to the page correctly.