MagentoMan
MagentoMan

Reputation: 573

Passing php variable to external javascript file

I have seen many solutions to this question on this site. However, nothing I try seems to be working.

In my php file I have this:

<?php
$monthlycalories = "[1, 1364, 1052, 922, 1, 1, 10, 1, 10, 10, 10, 265]";
?>

<script type="text/javascript">
  var test = "<?php echo $monthlycalories; ?>"; 
</script>

In my javascript file I have this:

$(function () {
var example = test;
alert(example);
        $('#monthly').highcharts({
            chart: {
                type: 'column'
            },
            title: {
                text: 'Monthly Calorie Intake'
            },
            xAxis: {
                categories: [
                    'Jan',
                    'Feb',
                    'Mar',
                    'Apr',
                    'May',
                    'Jun',
                    'Jul',
                    'Aug',
                    'Sep',
                    'Oct',
                    'Nov',
                    'Dec'
                ]
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Calories'
                }
            },
            tooltip: {
                headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                pointFormat: '<tr><td style="color:{series.color};padding:0"></td>' +
                    '<td style="padding:0"><b>{point.y:.1f} Calories</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [{
                name: 'Months',
                data: example

            }]
        });
    });

The javascript is a chart. I have been able to pass the info into the javascript file. I have used the alert() function and can see that it indeed brought the variable over. However, when I use the example variable in the javascript it does not work. Furthermore, if I copy over the alert results and replace data: example with data: [1, 1364, 1052, 922, 1, 1, 10, 1, 10, 10, 10, 265] then it works.

I can't understand why the variable example will not work but the chart works fine if you enter the info manually?

Upvotes: 3

Views: 7318

Answers (1)

sectus
sectus

Reputation: 15464

Try to remove quotes.

var test = <?php echo $monthlycalories; ?>; 

Upvotes: 6

Related Questions