Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

313
Visualizações
How to include a php file with javascript

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>
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

<?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.

about 4 years ago · Santiago Trujillo Relatório

0

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>
about 4 years ago · Santiago Trujillo Relatório

0

An alternative approach would be to save your dynamic php data to a html data-attribute like this:

<?php
$gender_arr =[
    'male',
    'female',
    'not_specify'
];
?>
<div id="gender-pie-user" data-series='<?php echo json_encode($gender_arr);?>'></div>

Example output:

<div id="gender-pie-user" data-series='["male","female","not_specify"]'></div>

This way you could save your chart init script as a static js file:

    let genderPie = document.querySelector("#gender-pie-user");
    
    // render chart if #genderPie element exists
    if(genderPie){
    
        let genderPieSeries = genderPie.getAttribute('data-series');
        var options = {
            chart: {
                height: 320,
                type: 'pie',
            }, 
            //parse data attribute
            series: JSON.parse(genderPieSeries),
            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(
            genderPie,
            options
        );
    
        chart.render();
    }

This way you can easily reuse your initializing function for different chart data views and benefit from static js file caching.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda