Transfer data form .php file to chart-data.js

I have this array:

$data_chart=[95,65,25,12,45,896,325];

in my php file and i want to insert this array (variable) into chart-data.js specially to this section:

var lineChartData = {
			labels : ["January","February","March","April","May","June","July"],
			datasets : [
				{
					label: "My First dataset",
					fillColor : "rgba(220,220,220,0.2)",
					strokeColor : "rgba(220,220,220,1)",
					pointColor : "rgba(220,220,220,1)",
					pointStrokeColor : "#fff",
					pointHighlightFill : "#fff",
					pointHighlightStroke : "rgba(220,220,220,1)",
					data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
				},
				{
					label: "My Second dataset",
					fillColor : "rgba(48, 164, 255, 0.2)",
					strokeColor : "rgba(48, 164, 255, 1)",
					pointColor : "rgba(48, 164, 255, 1)",
					pointStrokeColor : "#fff",
					pointHighlightFill : "#fff",
					pointHighlightStroke : "rgba(48, 164, 255, 1)",
					data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
				}
			]

		}

I have already done a script tag in my php file with this code

<script>
         var data=<?php $data_chart ?>;
        
        </script>

I can’t post the var data in my js file/How i can do this?

In your php code

$js_data = json_encode($data_chart);
echo "var js_data_chart =".$js_data;

Or something like that, anyway. How you create the JS variable will depend on where your JS is I guess. But you get the idea. json_encode the PHP array, then just pass it into a JS variable.

http://php.net/manual/en/function.json-encode.php

1 Like

[off topic]
if you are only displaying bar charts JavaScript libraries are not essential. Try SVG:

http://www.johns-jokes.com/downloads/sp-h/jb-svg-tooltips/svg-chart-tooltip-mouseover-001.php

http://www.johns-jokes.com/downloads/sp-h/jb-svg-tooltips/svg-chart-tooltip-hover-001.php

[/ot]

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.