Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

clat23's avatar

ChartJS not accepting string as data, how do I pass non-string

I have a function that draws a chart:

function drawYearlyChart(salesByMonth, expensesByMonth, netProfitByMonth)
        {
            var ctx = document.getElementById("salesVsExpensesChartYearly");
            var salesVsExpensesChartYearly = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                    datasets: [
                        {
                            label: 'Sales',
                            data: [salesByMonth],
...(truncated)

This does not work. I am suspecting that data: [salesByMonth], is interpreting the variable salesByMonth as a string -- for example: '1, 2, 3, 4, 5'.

When I try hard coding by doing data: ['1, 2, 3, 4, 5'], it fails, no chart drawn.

But when I try hard coding by doing data: [1, 2, 3, 4, 5], it works, chart is drawn as expected.

So my question is, how do I pass my variable salesByMonth so that ChartJS understands it?

0 likes
2 replies
Cinek's avatar
Cinek
Best Answer
Level 6

To data you should pass an array of values. If u have string '1, 2, 3, 4, 5' you can split it to array like this:

data: salesByMonth.split(', '); 
1 like
clat23's avatar

Ah man, I tried that at one point and it didn't work because this is how I did it:

data: [salesByMonth.split(', ')],

Your solution works. Thank you!

Please or to participate in this conversation.