I am trying to include javascript for my file index.php
, the problem is the javascript is inside a php file extension charts.php
and when I try to link the javascript to my index.php it dosent work, so how do I link charts.php
to index.php
?
I've tried
<script>
<?php include_once "../assets/js/charts.php";?>
</script>
as well as
<script src="../assets/js/charts.php"></script>
both of which don't work.
sample charts.php
<!-- Gender stats of user -->
<script type=''>
var options = {
chart: {
height: 320,
type: 'pie',
},
<?php echo "series: [$gender[0],$gender[1],$gender[2]],"?>
labels: ['Male','Female','Not specify'],
legend: {
show: true,
position: 'bottom',
horizontalAlign: 'center',
verticalAlign: 'middle',
floating: false,
fontSize: '14px',
offsetX: 0,
offsetY: 7
},
responsive: [{
breakpoint: 600,
options: {
chart: {
height: 240
},
legend: {
show: false
},
}
}]
}
var chart = new ApexCharts(
document.querySelector("#gender-pie-user"),
options
);
chart.render();
</script>
While charts.php
has a php file extension, its mostly Javascript with a few php variables from my database. I should note that if I included the charts.js
code directly inside index.php it works.
for example, this works:
// index.php
<script type=''>
var options = {
chart: {
height: 320,
type: 'pie',
},
<?php echo "series: [$gender[0],$gender[1],$gender[2]],"?>
labels: ['Male','Female','Not specify'],
legend: {
show: true,
position: 'bottom',
horizontalAlign: 'center',
verticalAlign: 'middle',
floating: false,
fontSize: '14px',
offsetX: 0,
offsetY: 7
},
responsive: [{
breakpoint: 600,
options: {
chart: {
height: 240
},
legend: {
show: false
},
}
}]
}
var chart = new ApexCharts(
document.querySelector("#gender-pie-user"),
options
);
chart.render();
</script>
While this does not work:
// index.php
<script src='../assets/js/charts.php'></script>
CodePudding user response:
PHP does not output content as default. So when you do this:
<script>
<?php include_once "../assets/js/charts.php";?>
</script>
you actually just includes the content from charts.php into memory, but never outputs it.
Something like this is more likely to work:
<script>
<?php echo require("../assets/js/charts.php");?>
</script>
CodePudding user response:
<?php require __DIR__ . "/../assets/js/charts.php";?>
Is the one that should be working. Switch it to require to see if the path can be resolved at all. I would also advice to start it with __DIR__
- make the path absolute.