Changing chart data dynamically with C# from SQL database - javascript

This is my chart code.
<!-- Graphs -->
<script src="../Scripts/Chart.min.js"></script>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
datasets: [{
data: [1, 6, 2, 5, 9, 5, 6],
label: "Issues Resolved",
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#007bff',
borderWidth: 4,
pointBackgroundColor: '#007bff'
}, {
data: [8, 5, 8, 6, 0, 2, 2],
label: "Issues Raised",
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#ff8400',
borderWidth: 4,
pointBackgroundColor: '#ff8400'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: true
},
title: {
display: true,
text: 'Issues Raised VS Issues Resolved'
}
}
});
</script>
This graph, though working fine, is static. What I want to ask is whether I can dynamically change the data (of which I'll always have 7 values, for each day of the week) in my datasets (of which I'll always have 2 values, for issues raised and issues resolved) from my .aspx.cs (which will get this data from my SQL Database) at runtime. And if so, how?
Thank you for your help.

I had a similar issue and found this solution. This solution requires you to use using System.Web.Services; and I will leave it to you to implement access to your SQL Database. But hopefully this solution can help you too!
Try using the following in the .ASPX file:
<!-- Graphs -->
<script src="../Scripts/Chart.min.js"></script>
<script>
$(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'BackendFileName.aspx/GetChartData', // change to your .aspx filename
data: '{}',
success: function (response) {
drawChart(response.d);
},
error: function () {
console.error("Error loading data! Please try again.");
}
});
})
function drawChart(dataValues) {
var issuesResolved = [];
var issuesRaised = [];
for (var i = 0; i < dataValues.length; i++) {
issuesResolved[i] = dataValues[i].issuesResolved;
issuesRaised[i] = dataValues[i].issuesRaised;
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
datasets: [{
data: issuesResolved,
label: "Issues Resolved",
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#007bff',
borderWidth: 4,
pointBackgroundColor: '#007bff'
}, {
data: issuesRaised,
label: "Issues Raised",
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#ff8400',
borderWidth: 4,
pointBackgroundColor: '#ff8400'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: true
},
title: {
display: true,
text: 'Issues Raised VS Issues Resolved'
}
}
});
}
</script>
Then add the following methods within backend file:
// Arbitrary class to hold required data from SQL Database
public class ChartDetails
{
public string IssuesResolved { get; set; }
public string IssuesRaised { get; set; }
public ChartDetails()
{
}
}
// Method that will be called by JQuery script
[WebMethod]
public static List<ChartDetails> GetChartData()
{
List<ChartDetails> dataList = new List<ChartDetails>();
// Access SQL Database Data
// Assign SQL Data to List<ChartDetails> dataList
return dataList;
}

You most certainly can. Take a look at the documentation here, you just need to implement the AJAX polling to see if the source dataset has changed.

I believe what you can do is:
Create a class level string variable in your code behind for holding the serialized array like
protected string weeklyData;
In Page_Load eventhandler, fetch the data from SQL database and populate an array of numbers int or decimal or floats depending upon your stored data. Lets say you end up with an array containing data
int[] data = [8, 5, 8, 6, 0, 2, 2];
Use the JavaScriptSerializer class to serialize it into a string and assign to weeklyData class variable like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
weeklyData = serializer.Serialize(data);
Assign weeklyData variable in your chart initialization code like:
data: <%= weeklyData %>,
enter code here
Another better option will be to write a WEB API service which will expose an endpoint for fetching the weekly data in json array format. Then, you can use jquery get method to get data and then initialize chart
$.get('{enpointurl}', function(weeklyData) {
//Write chart initialization code here and pass weekly data to chart data option
});

Add a hidden field:
<asp:HiddenField ID="hdnLabels" runat="server" Value="" />
<asp:HiddenField ID="hdnData" runat="server" Value="" />
In your chart script add:
labels: [<%= hdnLabels.Value %>],
datasets: [
{
data: [ <%= hdnData.Value %>],
... other options here,
}
]
In code behind:
public void ShowChartData()
string _data = "";
string _labels = "";
......Loop your SqlDataReader
....
....
while (dr.Read())
{
_labels = _data + dr["DayOfWeek"].ToString() + #",";
_data = _data + dr["DayOfWeekValue"].ToString() + #",";
}
_labels = _label.Remove(_label.Length - 1);
_data = _data.Remove(_data.Length - 1);
hdnLabels.Value = _labels;
hdnData.Value = _data;
}
Hope this helps...

Related

Python to chart.js

I have sqlite database with single table. I am trying to read data with Python and pandas and return the data as json file in a function. Then the goal is to use Javascript to fetch the json data and use it for chart.js.
Here is my Python Code that should read the data form the database:
#cherrypy.expose
def chart_data(self):
cnx = sqlite3.connect('Production.db', check_same_thread=False)
daily_df = pd.read_sql_query("SELECT * FROM data_object", cnx)
return daily_df.to_json()
Then here is the part of the JavaScript code that I am trying to use to fetch data from that python call:
function get_chart_data() {
fetch('/chart_data').then( x => {
return x.json();
}).then( x => {
console.log(x);
});
}
In this instance i am trying to print the data in console.log just to see if i am getting data from Python. However I need this data to be fed into chart.js
var data = {
labels: [],
datasets: [{
label: "Dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [],
}]
};
var options = {
maintainAspectRatio: false,
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
color: "rgba(255,99,132,0.2)"
}
}],
xAxes: [{
gridLines: {
display: false
}
}]
}
};
Chart.Bar('chart', {
options: options,
data: data
});
And finally, the sqilite table has these columns:timestamp,capacity,max_capacity, true_count.
There is only 24 rows of data, one for each hour of the day.
And here is where I am stuck. I am not sure how to properly pull this data into the chart. The goal is to plot true count over the 24h period.
With the code I have so far I know i am very close but i am missing something to make this work.
Am I pulling the data properly with javascript from python?
And how do i then push that json data in javascript into label variable and data variable in chart.js?
I have made some progress. I am now able to get data to javascript console log while using your ajax example.
/* chart.js chart examples */
$(document).ready(function(){
var _data;
var _labels;
$.ajax({
url: "chart_data",
type: "get",
success: function(response) {
full_data = JSON.parse(response);
_data = full_data['true_count'];
_labels = full_data['timestamp'];
},
});
// chart colors
var colors = ['#007bff','#28a745','#333333','#c3e6cb','#dc3545','#6c757d'];
/* large line chart */
var chLine = document.getElementById("chLine");
var chartData = {
labels:_labels,
datasets: [
{
data:_data,
backgroundColor: [
'rgba(42, 157, 244, 0.1)'
],
borderColor: [
'rgba(42, 157, 244, 1)',
'rgba(33, 145, 81, 0.2)',
],
borderWidth: 1
}]
};
if (chLine) {
new Chart(chLine, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false
}
}
});
}
;
});
So if i do console.log(full_data) i get my data from python in json format as i wanted. However, i am getting error that says: full_data is not defined at the line where I am saying that labels: full_data['timestamp']
It seems that my full data is not accessable from the chart block. I am sure i am misplacing few brackets to make this work but I am unable to figure out where.
Any ideas?
My json file looks like this:
[{"timestamp":"00:00:00.000000","true_count":0},{"timestamp":"01:00:00.000000","true_count":0},{"timestamp":"02:00:00.000000","true_count":0},{"timestamp":"03:00:00.000000","true_count":0},{"timestamp":"04:00:00.000000","true_count":0},{"timestamp":"05:00:00.000000","true_count":0},{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"15:00:00.000000","true_count":13},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"21:00:00.000000","true_count":10},{"timestamp":"22:00:00.000000","true_count":7},{"timestamp":"23:00:00.000000","true_count":4}]
I have been trying to parse this so timestamp goes to _labels and true_count goes to _data but no luck.
Here is what i have:
$(document).ready(function(){
var _data =[];
var _labels = [];
$.ajax({
url: "chart_data",
type: "get",
success: function(response) {
full_data = JSON.parse(response);
full_data.forEach(function(key,index){
_data = key.true_count;
_labels= key.timestamp;
});
//_data = [full_data['true_count']];
//_labels = [full_data['timestamp']];
},
});
Any suggestion what am I doing wrong now?
I am sharing my example which I used using Google charts .I am fetching live data from OPC Server using ajax and updated my real-time graph. It won't be a big difference if you use database instead of opc server. I hope you can relate it with your example.
Html
<div class="row" id="grap">
<div class="col-lg-12">
<div class="row">
<div class="col-12">
<div class="card">
<div class="chart-wrapper">
<div id="graph"></div>
</div>
</div>
</div>
</div>
</div>
</div>
This is django file from where I am passing data to gettemp() function via ajax call in json format. In your case it is database and there wont be issue.
Views.py
def plcdata(request):
url="opc.tcp://127.0.0.1:9000"
client=Client(url)
client.connect()
print("Client Connected")
data={}
dt=[]
while True:
pres=client.get_node("ns=2;i=2")
Pressure=pres.get_value()
adp=client.get_node("ns=2;i=3")
ap=adp.get_value()
rh=client.get_node("ns=2;i=4")
r=rh.get_value()
sp=client.get_node("ns=2;i=5")
s=sp.get_value()
nitro=client.get_node("ns=2;i=6")
n=nitro.get_value()
o2n=client.get_node("ns=2;i=7")
o=o2n.get_value()
hgl=client.get_node("ns=2;i=8")
h=hgl.get_value()
stempress=client.get_node("ns=2;i=9")
sps=stempress.get_value()
cond=client.get_node("ns=2;i=10")
co=cond.get_value()
dmwp=client.get_node("ns=2;i=11")
dmp=dmwp.get_value()
dmwf=client.get_node("ns=2;i=12")
dmf=dmwf.get_value()
chwp=client.get_node("ns=2;i=13")
chp=chwp.get_value()
chwt=client.get_node("ns=2;i=14")
cht=chwt.get_value()
icp=client.get_node("ns=2;i=16")
ip=icp.get_value()
icf=client.get_node("ns=2;i=15")
iff=icf.get_value()
ict=client.get_node("ns=2;i=17")
it=ict.get_value()
dcpp=client.get_node("ns=2;i=19")
dpp=dcpp.get_value()
dcff=client.get_node("ns=2;i=18")
dff=dcff.get_value()
dctt=client.get_node("ns=2;i=20")
dtt=dctt.get_value()
#Time=client.get_node("ns=2;i=3")
#Ti=Time.get_value()
#Ti1=datetime.time(Ti.hour,Ti.minute,Ti.second)
ti=datetime.now()
ti1=(str(ti.strftime('%Y-%m-%d %H:%M:%S')))
dt.append(str(Pressure)+','+ti1+','+str(ap)+','+str(r)+','+str(s)+','+str(n)+','+str(o)+','+str(h)+','+str(sps)+','+str(co)+','+str(dmp)+','+str(dmf)+','+str(chp)+','+str(cht)+','+str(ip)+','+str(it)+','+str(iff)+','+str(dpp)+','+str(dtt)+','+str(dff))
data['final']=dt
return JsonResponse(data)
Please check the getTemp() function as data is recieved from django in the success function. This is the part where you will have to make changes as per your requirement.
JS
<script type="text/javascript">
google.charts.load('current', {
callback: function () {
var chart = new google.visualization.LineChart(document.getElementById('graph'));
var options = {'title' : 'CTL-2 AIR PRESSURE (Bar)',
titleTextStyle: {
fontName: "Arial",
fontSize: 18,
},
animation: {
duration: 1000,
easing: 'out',
startup: true
},
hAxis: {
title: 'Time',
format: "HH:mm:ss",
textStyle: {
fontSize : 14,
bold:'true',
},
},
vAxis: {
title: 'Air Pressure',
format: '0.00',
textStyle: {
fontSize : 14,
bold:'true',
},
},
height: 450,
width:1000,
legend:'bottom'
};
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Air Pressure');
var go=[];
function getTemp() {
$.ajax({
type:"get",
url:"{% url 'plcdata' %}",
success:function(dat){
for(i=0;i<dat.final.length;i++){
var go=dat.final[i].split(',');
var tm = new Date();
if(data.hg.length>15){
data.removeRow(0);
}
data.addRow([tm, Number(go[0])]);
chart.draw(data, options);
}
return dat;
},
error: function(){
console.log("Error Occurred");
}
})
}
getTemp();
setInterval(getTemp, 3000);
},
packages:['corechart']
});
</script>
[1]: https://i.stack.imgur.com/bMWVB.png

Charts.js + Django date on X-Axis

I do fear that similar questions have been asked in the past, however I was not able to derive a solution for my specific issue.
I am sending data from a Django function to Charts.js
The chart gets rendered correctly and displays with the exception of the date formatting on the X-Axis.
Django Data:
'''class UnitChartData(APIView):
def get(self, request, format=None):
material_code = request.session['material_code']
plant_code = request.session['plant_code']
qs_mat = DPoList.objects.filter(plant_code=plant_code).filter(material_code=material_code).order_by('delivery_date')
unit_price_list=[]
for items in qs_mat:
if items.gr_received is None or items.invoiced_usd is None:
unit_price = 0
unit_price_list.append(unit_price)
else:
unit_price=items.invoiced_usd/items.gr_received
unit_price_list.append(unit_price)
date_list=[]
for items in qs_mat:
date_list.append(items.delivery_date)
labels = date_list
default_items = unit_price_list
data = {
"labels": labels,
"default": default_items,
}
return Response(data)'''
Chart.js script
'''var endpoint = '/d/api/unitchart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.default
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'PO#',
data: defaultData,
fill: false,
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
options: {
responsive: true,
legend: {
position: 'bottom',
},
hover: {
mode: 'label'
},
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
min: 2
}
}]
}
}
});
}'''
The Django Datetime object turns into an ISO date format: 2016-08-05T04undefined000Z - this is what gets displayed instead of just the month or date on the X-Axis.
I am trying to change that in the Javascript, either in the Charts.js or an additional function. from what I could find on Stackoverflow you can convert the date format through moments.js and in a second step set the xAxis to:
'''options: { scales: { xAxes: { type: 'time' } } }'''
However, I have not been ale to figure out how to do that and certainly not in an efficient way, any help would be greatly appreciated.

Uncaught type error: mychart.update is not a function

I am building external buttons to toggle the visibility of data from chartjs, but it will only works when the screen size changed. So, I found that can use mychart.update() to solve the problem. But it get me the error that I stated in the title.
Here is my chart:
var myRadarChart = {
type: 'radar',
data: {
labels: lbl,
datasets: [
{
label: 'Houses',
data: yh,
backgroundColor:['rgba(0, 123, 255, 0.5)'],
borderColor: ['rgba(0, 123, 255, 0.8)'],
hidden:false
},
{
label: 'Apartments',
data: ya,
backgroundColor:['rgba(40,167,69, 0.5)'],
borderColor: ['rgba(40,167,69, 0.8)'],
hidden:false
},
{
label: 'Rooms',
data: yr,
backgroundColor:['rgba(218, 17, 61,0.5)'],
borderColor: ['rgba(218,17,61,0.8)'],
hidden:false
}
]
},
options: {
legend:{
display:true,
onHover: function(event, legendItem) {
document.getElementById("myRadarChart").style.cursor = 'pointer';},
},
maintainAspectRatio:false,
scale: {
angleLines: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 0
}
}
}
};
var ctx = document.getElementById('myRadarChart').getContext('2d');
new Chart(ctx, myRadarChart);
And how I trying to do is:
//Onclick
function getData(dontHide){
switch(dontHide){
case 0:
myRadarChart.data.datasets[0].hidden=false;
myRadarChart.data.datasets[1].hidden=true;
myRadarChart.data.datasets[2].hidden=true;
myRadarChart.update();
break;
case 1:
myRadarChart.data.datasets[0].hidden=true;
myRadarChart.data.datasets[1].hidden=false;
myRadarChart.data.datasets[2].hidden=true;
myRadarChart.update();
break;
case 2:
myRadarChart.data.datasets[0].hidden=true;
myRadarChart.data.datasets[1].hidden=true;
myRadarChart.data.datasets[2].hidden=false;
myRadarChart.update();
break;
}
}
Or is there alternative ways to perform something like this?
Your issue is that you're trying to call the .update() method on your graph's config object, not your actual graph instance. As you can see, myRadarChart is just an object, it doesn't have a method called update() on it. However, the graph you create when doing new Chart(ctx, myRadarChart); does give you the .update() method.
To fix your issue, you'll need to first store the instance of your graph somewhere:
var radarGraph = new Chart(ctx, myRadarChart);
Then update the graph's data (rather than your config object directly):
radarGraph.data.datasets[0].hidden = false;
...
Then call the update method on your radarGraph object:
radarGraph.update();

Label not showing in Chart.js with Grails

I wish to pass data from a Grails controller to a chart.js chart in a Grails view. My code will not display the chart labels correctly.
The issue is that labels (an arrayList of dates) is not being read correctly as an array of strings in Javascript which is causing Chart.js not to display.
Can anyone offer any help?
Any help would be gratefully received. Thanks in advance!
My code is here:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script>
var userResult = ${userResultMap as JSON};
var data = userResult.result;
var labels = userResult.dateCreated;
var config = {
type: 'line',
data: {
labels: testDate,
datasets: [{
label: 'Clinical FRE',
backgroundColor: '#7A564A',
borderColor: '#7A564A',
data: result,
fill: false
}]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
responsive: true,
scales: {
yAxes: [{
gridLines: {
drawBorder: false,
color: ['#9b1f22', '#9b1f22', '#ed1c24', '#ed1c24', '#f7931f', '#f7931f', '#206b36', '#206b36', '#206b36', '#206b36', '#206b36']
},
ticks: {
min: 0,
max: 100,
stepSize: 10,
callback: function (value) {
return value + "%"
}
}
}]
}
}
};
window.onload = function createChart(data) {
var ctx = document.getElementById('myChart').getContext('2d');
window.myLine = new Chart(ctx, config)
};
</script>
Data is sent from controller using ModelandView command:
#Secured('ROLE_USER')
def home() {
try {
SecUser user = springSecurityService.currentUser
Participant p = Participant.findByUser(user)
Result userResults = Result.findByUser(user)
def userResultsList
def riskLevelMap
def iconClassMapList = []
def riskLevelMapList = []
def colourNameList = []
Map userResultMap = [:]
if (userResults!= null){
userResultsList = userResults.list()
if(userResultsList != null)
userResultsList.each {list->
iconClassMapList.add(previousTestsService?.getIconType(list))
riskLevelMap = riskAdviceService?.riskLevel(list.result)
riskLevelMapList.add(riskLevelMapList)
colourNameList.add(riskLevelMap?.colourName)
}
userResultMap.put("result",userResultsList?.result)
userResultMap.put("dateCreated",userResultsList?.dateCreated)
println userResultMap
println userResultsList.dateCreated
println(userResultsList.dateCreated.getClass())
}
return new ModelAndView('home', [user: user, participant: p, username: user.username,userResultsList: userResultsList,iconClassMapList:iconClassMapList,colourNameList:colourNameList,userResultMap:userResultMap])
} catch (Exception ex) {
log.error(ex.printStackTrace())
}
}
Sample data:
data - [13.7]
labels - [2018-09-17 16:39:00.0]
The main issue here is that grails automatically escapes values as HTML upon insertion in the GSP page. You can suppress this by adding the advice
<%# expressionCodec="none" %>
at the beginning of the GSP page.
Be aware that your application will be less secure after the change. Especially if the data can contain user-created input people might start messing with your application.
Here is a running example using Grails 3.3.8 based on the test data supplied by #Kumar Chapagain, thank you very much.
In the controller you don't need to package the data in a ModelAndView, as this is done automatically by Grails. Just return a map with the needed entries. I prefer to convert the map to JSON within the controller and not in the gsp page as it keeps the control where it belongs and the GSP more simple.
Controller:
package g338
import grails.converters.JSON
class ChartController {
def index() {
Map userResultMap = [:]
List dateCreated = ["2018-09-17 13:07:06.0","2018-09-17 13:27:06.0","2018-09-17 14:27:06.0","2018-09-17 17:27:06.0"]
List result = [50, 56, 23, 42]
userResultMap.put("dateCreated",dateCreated)
userResultMap.put("result",result)
[ userResultMap: userResultMap as JSON ]
}
}
gsp page: views/chart/index.gsp
<%# expressionCodec="none" %>
<!doctype html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Welcome to Grails</title>
</head>
<body>
<canvas id="myChart"></canvas>
<g:javascript>
var result = ${userResultMap};
var data = result.result;
var labels = result.dateCreated;
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Clinical FRE',
backgroundColor: '#7A564A',
borderColor: '#7A564A',
data: result,
fill: false
}]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
responsive: true,
scales: {
yAxes: [{
gridLines: {
drawBorder: false,
color: ['#9b1f22', '#9b1f22', '#ed1c24', '#ed1c24', '#f7931f', '#f7931f', '#206b36', '#206b36', '#206b36', '#206b36', '#206b36']
},
ticks: {
min: 0,
max: 100,
stepSize: 10,
callback: function (value) {
return value + "%"
}
}
}]
}
}
};
window.onload = function createChart(data) {
var ctx = document.getElementById('myChart').getContext('2d');
window.myLine = new Chart(ctx, config)
};
</g:javascript>
</body>
</html>
Make sure userResultsList(userListMap) data must be in the form below from the controller.
Map userResultMap = [:]
List dateCreated = ["2018-09-17 13:07:06.0","2018-09-17 13:27:06.0","2018-09-17 14:27:06.0","2018-09-17 17:27:06.0"]
List result = [50, 56, 23, 42]
userResultMap.put("dateCreated",dateCreated)
userResultMap.put("result",result)
Then you need to parse the userResultMap data as JSON if not parsed and do similar like this in gsp page:
<script>
var userResult = ${userResultMap as JSON};
var result = userResult.result;
var labels = userResult.dateCreated;
</script>
You would need to convert your array, object whatever you are using to JSON for JavaScript to understand it.
<g:javascript>
var testDate = ${userResultsList.dateCreated}
var result = ${userResultsList.result as JSON} // make sure grails.converters.JSON is imported
</g:javascript>
var labels = userResult.dateCreated;
var config = {
type: 'line',
data: {
labels: testDate,
you are using labels: testDate,
but assigning labels to labels
try
var testDate = userResult.dateCreated;
**labels: testDate**

How do I implement Laravel Analytics with Chart.js

Hi guys I am busy building a dashboard for my website and I want to add a chart that shows the sessions for the last 7 days. I have already setup my service account and I am receiving the data. Here is the output I receive:
[
{"date":{"date":"2016-08-22 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"0","pageViews":"0"},
{"date":{"date":"2016-08-23 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"0","pageViews":"0"},
{"date":{"date":"2016-08-24 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"0","pageViews":"0"},
{"date":{"date":"2016-08-25 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"0","pageViews":"0"},
{"date":{"date":"2016-08-26 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"0","pageViews":"0"},
{"date":{"date":"2016-08-27 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"0","pageViews":"0"},
{"date":{"date":"2016-08-28 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"0","pageViews":"0"},
{"date":{"date":"2016-08-29 15:38:36.000000","timezone_type":3,"timezone":"UTC"},"visitors":"1","pageViews":"5"}
]
My Controller function is like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use LaravelAnalytics;
class AdminController extends Controller
{
public function index(){
$analytics = LaravelAnalytics::getVisitorsAndPageViews(7);
return view('admin.index')
->with(json_encode($analytics));
}
}
I forgot to mention that I am using the Spatie\Laravel-Analytics library.
My Javascript looks like this to render a demo chart.
var ctx = document.getElementById("sessions");
var sessions = new Chart(ctx, {
type: 'line',
data: {
labels: ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
datasets: [{
label: 'Sessions Last 7 Days',
data: [4,8, 19, 3, 5, 4, 3],
backgroundColor: [
'rgba(52, 73, 94,0.2)'
],
borderColor: [
'rgba(52, 73, 94,1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
My question is how do I get the data received from json to display in the chart?
if you already have a json object/file you can get the data with json.parse(json var) , it will return you the data
You take 7 from your controller but the output is 8, check that also. And In your JS
var myData = [
#foreach($analytics as $analis)
{{ $analis->visitors }}, //remeber to put comma (,) at end for array
#endforeach
]
data: {
datasets: [{
data: myData,
}]
},

Categories

Resources