Beekeeper Beekeeper - 3 months ago 9
PHP Question

Json to Chart.js not working

We got this file from the Internet and somehow we can able to get the output as

JSON
in the
console
but the
chartdisplay.js
is not taking the
JSON
file.

Can you help me.

Thanks!

HTML

<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/chartjs/chart.js"></script>
<script type="text/javascript" src="chartdisplay.js"></script>

<div class="chart-container"> <!-- we have defined width and height for this class -->
<canvas id="mycanvas"></canvas>
</div>


content.php

<?php
//get connection
$mysqli = new mysqli('localhost','root','','beehive_exp');

if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}

$query = sprintf("SELECT userid, facebook, twitter, googleplus FROM followers");

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);


chartdisplay.js

$(document).ready(function(){
$.ajax({
url : "http://192.100.1.100/content.php",
type : "GET",
success : function(data){
console.log(data);

var userid = [];
var facebook_follower = [];
var twitter_follower = [];
var googleplus_follower = [];

for(var i in data) {
userid.push("UserID " + data[i].userid);
facebook_follower.push(data[i].facebook);
twitter_follower.push(data[i].twitter);
googleplus_follower.push(data[i].googleplus);
}

var chartdata = {
labels: userid,
datasets: [
{
label: "facebook",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(59, 89, 152, 0.75)",
borderColor: "rgba(59, 89, 152, 1)",
pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
pointHoverBorderColor: "rgba(59, 89, 152, 1)",
data: facebook_follower
},
{
label: "twitter",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(29, 202, 255, 0.75)",
borderColor: "rgba(29, 202, 255, 1)",
pointHoverBackgroundColor: "rgba(29, 202, 255, 1)",
pointHoverBorderColor: "rgba(29, 202, 255, 1)",
data: twitter_follower
},
{
label: "googleplus",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(211, 72, 54, 0.75)",
borderColor: "rgba(211, 72, 54, 1)",
pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
pointHoverBorderColor: "rgba(211, 72, 54, 1)",
data: googleplus_follower
}
]
};

var ctx = $("#mycanvas");

var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error : function(data) {
}
});
});


This is what we get

enter image description here

JSON output

enter image description here

PHP Output

enter image description here

Answer

We continued in the chat and the problem I found was that the data he was getting from the php file was in JSON string.

So, in first line of success function, I wrote

data = JSON.parse(data);

and the same code worked after and showed the graph as expected.