How to pass result from php to javascript to display on chart


I am able to fetch my database values in php using below code.

	$connect = mysqli_connect("localhost", "root","", "sensor_data");
	$sql = "SELECT * FROM sdata ORDER BY ID DESC LIMIT 5;";
	$response = mysqli_query($connect, $sql) or die(mysqli_error($connect));
	while($row = mysqli_fetch_assoc($response)){
        $r[]= $row;
         echo json_encode($r, JSON_NUMERIC_CHECK);


Here i am able to see the echo’ed result on my php page…Now i want to pass this $r value to the CanvasJS.Chart chart container…

                       data: [{
				type: "line",
				dataPoints: ?????here i want to pass the $r result as one of the parameter say x: to the chart...How is it possible...

use mysqli_fetch_all() to get everything, then put this all through json_encode() and echo it at the place you want it.

Hi chorn, thanks for the reply…Yes i did what you said and I am able to display those values using
echo json_encode($r1, JSON_NUMERIC_CHECK);…But my question is how do i pass these values to the x: dataPoints in javascript canvas.js as shown in the below code…

<script type="text/javascript">
	window.onload = function() {

  var dps = [{x: "HOW DO I GET THE VALUES WHICH I HAVE RECEIVED IN PHP using echo json_encode() HERE", y: "20"}]; 

var chart = new CanvasJS.Chart("chartContainer", {
			title: {
				text: "Line Chart"
			axisX: {

				interval: 1,
				title: "Time",
				//valueFormatString: "hh:mm TT",
			axisY: {

				interval: 5,
				title: "Temp"
			data: [{
				type: "line",
				dataPoints: dps///////(HERE I AM GETTING THE VALUES OF x and y THROUGH THE VARIABLE dps)...
	<script src="canvasjs.min.js"></script>

Plz help me out…

Have you called the PHP code using Ajax, or is the JS contained in-line within the output from the PHP?

yes it is contained in-line php…

Then just var dps = <?php echo json_encode(...); ?> ...

I tried that as well but no result showing in my line graph:

<script src="canvasjs.min.js"></script>

But no results on the Chart when i run the page… :frowning:

Does your JSON have the specific format the Javascript requires? How does it look like compared to demo data?

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