This question already has an answer here:
Hi I have a fair experience in javascript and I am stuck in the following situation.
I am developing a PHP page to display some values in a graph. I am using morris.js.
Now as morris.js uses array in following format to display as a graph:
// AREA CHART
var area = new Morris.Area({
element: 'revenue-chart',
resize: true,
data: [
{y: '2011', purchase: 500, sale: 1000, profit: 500},
{y: '2012', purchase: 600, sale: 1100, profit: 500},
{y: '2013', purchase: 500, sale: 1050, profit: 550}
],
xkey: 'y',
ykeys: ['profit', 'purchase', 'sale'],
labels: ['Profit', 'Purchase', 'Sale'],
lineColors: ['#a0d0e0', '#3c8dbc', '#ac5bc3'],
hideHover: 'auto'
});
But I have those values in php variable like:
$year1 = '2011';
$sale1 = '1000';
$purchase1 = '500';
$profit1 = '500';
$year2 = '2012';
$sale2 = '1200';
$purchase2 = '600';
$profit2 = '500';
$year3 = '2013';
$sale3 = '1050';
$purchase3 = '500';
$profit3 = '550';
How can I pass those php values to js. I tried json_encode() but it didn't work form me.
UPDATE: Displaying updated code with Luke Cordingley's answer, still have problem with it.
<script type="text/javascript">
window.MyProjectNamespace.phpVars = <?
$phpVars = array('year' => '2011', 'purchase' => '1000', 'sale' => '600', 'profit' => '400');
echo json_encode($phpVars);
?>
</script>
<script type="text/javascript">
$(function() {
// AREA CHART
var area = new Morris.Area({
element: 'revenue-chart',
resize: true,
data: [
{y: window.MyProjectNamespace.phpVars.year, purchase: "500", sale: "1000", profit: "500"},
{y: "2012", purchase: "600", sale: "1100", profit: "500"},
{y: "2013", purchase: "500", sale: "1050", profit: "550"}
],
xkey: 'y',
ykeys: ['profit', 'purchase', 'sale'],
labels: ['Profit', 'Purchase', 'Sale'],
lineColors: ['#a0d0e0', '#3c8dbc', '#000000'],
hideHover: 'auto'
});
});
</div>