Vuejs + Chartjs not showing chart - laravel-5

I’m having problem displaying the chart, Although the data in the getGender() is right, the chart is not displayed. If I get data outside axios it return no data even though I have set it in response.
<div class="x_content">
<canvas id="myChart"></canvas>
</div>
<script>
export default{
props: ['initialCounter'],
data(){
return{
gender:{},
}
},
mounted(){
axios.get('get-gender')
.then((response)=>{
this.getGender(response.data[0])
})
},
methods:{
getGender(data){
console.log(this.gender)
var ctx = document.getElementById("myChart")
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Male", "Female"],
datasets: [{
label: '# of Votes',
data: [data.male,data.female],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
});
}
}
}
</script>

Related

cann't make Chart when convertting View MVC to PDF

I am trying to convert the output of MVC view to PDF. I could do that by Rotativa pretty good by using this video
https://www.youtube.com/watch?v=VkHcG24nM8U
but there is still a problem. in the view I am creating a radar chart dynamically. which when the pdf is created it is missing. is it possible to make chart when converting view to PDF file?
This is the code for making Rotativa viewTo PDF
public async Task<IActionResult> PrintPDF(long wId, long cId, long pId, long aId, short no)
{
var result = await _accessmentFacad.GetAssessmentResultForUserByIdService.Execute(wId, cId, pId, aId, no);
return new ViewAsPdf("PrintPDF", result)
{
FileName ="sample.pdf",
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
PageSize = Rotativa.AspNetCore.Options.Size.A4,
};
}
and using this jquery radarchart code for creating the chart
<script>
var BeforeWorkshop = []; //these are javascript array variables
var AfterWorkshop = [];
#if(Model.ResultCategoriesDtos.Count>0)
{
foreach(var item in Model.ResultCategoriesDtos)
{
#:BeforeWorkshop.push(#item.Answer3_1);
#:AfterWorkshop.push(#item.Answer3_2);
}
}
var RadarChart = document.getElementById('radarchart').getContext('2d');
var chart = new Chart(RadarChart, {
type: 'radar',
data: {
labels: ["1Lesson", "2Lesson","3Lesson", "4Lesson", "5Lesson"],//x axis labels
datasets: [{
label: "First",
data: BeforeWorkshop,
fill: true,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 255)',
pointBackgroundColor: 'rgb(255, 99, 132)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)',
}
, {
label: "Second",
data: AfterWorkshop,
fill: true,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgb(54, 162, 235)',
pointBackgroundColor: 'rgb(54, 162, 235)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(54, 162, 235)'
}
]
},
// Configuration options
options: {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ": " + tooltipItem.yLabel;
}
}
}
}
});
</script>

how to display multiple sum with chart js and laravel?

I have three table
Table drics
Table country_dric
Table Countries
I just display country name with sum legal from table drics.
I want to display sum column legal, illegal, applicant and mandatory from table drics with country name.
How to display the sum of each column from table drics?
my controller
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric[$key]=$value->sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js Code
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: '# ',
data: #json($dric),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
Try this
Your controller:
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as legal_sum')
,\DB::raw('sum(ilegal) as ilegal_sum')
,\DB::raw('sum(applicant) as applicant_sum')
,\DB::raw('sum(mandatory) as mandatory_sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric['legal'][$key]=$value->legal_sum;
$dric['ilegal'][$key]=$value->ilegal_sum;
$dric['applicant'][$key]=$value->applicant_sum;
$dric['mandatory'][$key]=$value->mandatory_sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js code:
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: 'Legal',
data: #json($dric['legal']),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Ilegal',
data: #json($dric['ilegal']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Applicant',
data: #json($dric['applicant']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Mandatory',
data: #json($dric['mandatory']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
You can use #foreach loop if you want too

I want to show project name & hours on chart js using Laravel

I am a beginner at Laravel I am trying to show project name and hours on the chart.js. Unfortunately, data is not showing on the chart; how can I show that?
controller
Chart script
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
#foreach($hour_logs as $key=>$value)
data: {
//labels: ['Red','Purple'],
labels: {{$value}},
datasets: [{
data: {{$value}},
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
#endforeach
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
return response
[
"Joylinkhk: 13,",
"HorizonTechnologies: 2,",
"Alahazrat: 9,",
"j2w: 0,"
]
on the left side project name and on the right side hours
dd($hour_logs)
array:4 [
0 => "Joylinkhk: 13,"
1 => "HorizonTechnologies: 2,"
2 => "Alahazrat: 9,"
3 => "j2w: 0,"
]
When passing complex data structures from PHP to JavaScript you will most likely want to be converting them to JSON.
You can convert arrays to JSON using json_encode(). If you are using Larvel collections, they can be converted using ->toJson().
Use Following code
You must send data from controller by parsing like this
implode(',', $label) and
implode(',', $value)
<script>
let label = {!! $label !!}
let value = {!! $value !!}
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
#foreach($hour_logs as $key=>$value)
data: {
//labels: ['Red','Purple'],
labels: label.split(','),
datasets: [{
data: value.aplit(,),
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
#endforeach
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

How to pass data in Laravel with Chart.js

I want to display total of men and woman from learnings table in chart using Chartjs in Laravel.
My controller
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
$learning = $men_learning + $women_learning ;
return view('home', compact('learning'));
}
My script in blade view.
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['total'],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
How can I propagate loaded statistic from my script to the chart?
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
return view('home', compact('men_learning', 'women_learning'));
}
<script type="text/javascript">
$(function(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Men', 'Women'],
datasets: [{
label: 'Men',
data: [{!!$men_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(40,167,69,1)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0 ,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(254,86,83,.8)',
},
{
label: 'Women',
data: [{!!$women_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(220,53,69,.8)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(63,82,227,.8)',
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
display: true,
drawBorder: false,
color: '#f2f2f2',
},
ticks: {
beginAtZero: true,
stepSize: 100,
callback: function(value, index, values) {
return value;
}
}
}],
xAxes: [{
gridLines: {
display: false,
tickMarkLength: 15,
}
}]
},
}
});
});
</script>

Ajax call time to load in django application

I am developing a django app using the Django Rest Framework with chart.JS in order to render some chart.
My ajax call is taking a long long long time and I am on local..
Is there a way to check what is taking so long in order to know where to look in order to refactor ?
it takes on average on local between 10 and 15 second each time..
Here is my code for example:
<script>
var endpoint = 'api/chart/data2'
$('.ajaxProgress').show();
$('.dashboard-container').hide();
function getAvg(grades) {
return grades.reduce(function (p, c) {
return p + c;
}) / grades.length;
}
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
complete_data = data.team_complete,
info_data = data.team_info_score,
motiv_data = data.team_motiv_score,
action_data = data.team_action_score,
behaviour_data = data.team_behaviour_score,
user_list = data.users,
user_dist = data.user_dist,
info_dist = data.info_dist,
motiv_dist = data.motiv_dist,
action_dist = data.action_dist,
behav_dist = data.behav_dist,
info_label = data.info_label,
motivation_label = data.motivation_label,
action_label = data.action_label,
behav_label = data.behav_label,
complete_label = data.complete_label,
cohesiveness_score = data.cohesiveness_score
var bar_color = [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 220, 89, 0.2)',
'rgba(255, 192, 35, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 220, 89, 0.2)',
'rgba(255, 192, 35, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(255, 99, 132, 0.2)'
]
var ctx = document.getElementById("mainGraph").getContext('2d');
var ctx2 = document.getElementById("mainGraph2").getContext('2d');
var ctx3 = document.getElementById("mainGraphLine1").getContext('2d');
var ctx4 = document.getElementById("mainGraphLine2").getContext('2d');
var ctx5 = document.getElementById("mainGraphLine3").getContext('2d');
var ctx6 = document.getElementById("mainGraphLine4").getContext('2d');
$('.ajaxProgress').hide();
$('.dashboard-container').show();
var canvas = document.getElementById("mainGraph");
var mainGraph = new Chart(ctx, {
type: 'bar',
data: {
labels: complete_label,
datasets: [{
data: complete_data,
backgroundColor: bar_color ,
}]
},
options: {
legend: {
position: 'top',
display: false
},
responsive:true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {autoSkip: false}
}]
}
},
});
//end graph 1//
canvas.onclick = function(evt) {
var activePoints = mainGraph.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var str_label = label.toString()
console.log(str_label)
var value = chartData.datasets[0].data[idx];
if(label == "General,Details"){
$('#general').modal('show');
} else if(label == "Sameness,Difference"){
$('#sameness').modal('show');
} else if(label == "Visual,Auditory"){
$('#visual').modal('show');
} else if(label == "Static,Process"){
$('#static').modal('show');
} else if(label == "Best Scenario,Worst Scenario"){
$('#bestScenario').modal('show');
} else if(label == "Binary,Shades"){
$('#binary').modal('show');
} else if(label == "External,Internal"){
$('#external').modal('show');
} else if(label == "Go Away,Toward"){
$('#goAway').modal('show');
} else if(label == "Things"){
$('#things').modal('show');
} else if(label == "Variety,Routine"){
$('#variety').modal('show');
} else if(label == "Active,Reaction"){
$('#active').modal('show');
} else if(label == "Manager worker"){
$('#manager').modal('show');
} else if(label == "Option,Procedure"){
$('#option').modal('show');
} else if(label == "Perfection,Optimizing"){
$('#perfection').modal('show');
} else if(label == "Sensor,Intuition"){
$('#sensor').modal('show');
} else if(label == "External locus,Internal locus"){
$('#locus').modal('show');
} else if(label == "Strong Will,Compliant"){
$('#will').modal('show');
} else if(label == "In time,Through time"){
$('#time').modal('show');
} else{
$('#modeling').modal('show');
}
}}
;
//graph 2 //
var mainGraph2 = new Chart(ctx2, {
type: 'horizontalBar',
data: {
labels: user_list,
datasets: [{
data: user_dist,
backgroundColor: bar_color ,
}]
},
options: {
legend: {
position: 'top',
display: false
},
responsive:true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {autoSkip: false,
beginAtZero: true,
min: 0,
max:100,
}
}]
},
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
value: getAvg(user_dist),
borderColor: "rgba(216, 138, 138, 1)",
label: {
content: "AVERAGE",
fontFamily:'Ubuntu',
enabled: true,
position: "middle",
fontSize: 10,
backgroundColor: 'rgba(0,0,0,0.5)',
}
}
]
}
},
});
//end graph 2//
//graph 3 //
var mainGraphLine1 = new Chart(ctx3, {
type: 'line',
data: {
labels: info_label,
datasets: [{
data: info_dist,
backgroundColor: 'rgba(102, 187, 158, 0.2)' ,
}]
},
options: {
legend: {
position: 'top',
display: false
},
responsive:true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {autoSkip: false,
beginAtZero: true,
}
}],
yAxes: [{
ticks: {min: 0, max:100}
}],
},
annotation: {
annotations: [
{
type: "line",
mode: "horizontal",
scaleID: "y-axis-0",
value: getAvg(info_dist),
borderColor: "rgba(216, 138, 138, 1)",
borderWidth: 0.5,
label: {
content: "AVERAGE",
fontFamily:'Ubuntu',
enabled: true,
position: "middle",
fontSize: 8,
backgroundColor: 'rgba(0,0,0,0.5)',
}
}
]
}
},
});
//end graph 3//
//graph 4 //
var mainGraphLine2 = new Chart(ctx4, {
type: 'line',
data: {
labels: motivation_label,
datasets: [{
data: motiv_dist,
backgroundColor: 'rgba(102, 187, 158, 0.2)' ,
}]
},
options: {
legend: {
position: 'top',
display: false
},
responsive:true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {autoSkip: false,
beginAtZero: true,
}
}],
yAxes: [{
ticks: {min: 0, max:100}
}],
},
annotation: {
annotations: [
{
type: "line",
mode: "horizontal",
scaleID: "y-axis-0",
value: getAvg(motiv_dist),
borderColor: "rgba(216, 138, 138, 1)",
borderWidth: 0.5,
label: {
content: "AVERAGE",
fontFamily:'Ubuntu',
enabled: true,
position: "middle",
fontSize: 8,
backgroundColor: 'rgba(0,0,0,0.5)',
}
}
]
}
},
});
//end graph 4//
//graph 5 //
var mainGraphLine3 = new Chart(ctx5, {
type: 'line',
data: {
labels: action_label,
datasets: [{
data: action_dist,
backgroundColor: 'rgba(102, 187, 158, 0.2)' ,
}]
},
options: {
legend: {
position: 'top',
display: false
},
responsive:true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {autoSkip: false,
beginAtZero: true,
}
}],
yAxes: [{
ticks: {min: 0, max:100}
}],
},
annotation: {
annotations: [
{
type: "line",
mode: "horizontal",
scaleID: "y-axis-0",
value: getAvg(action_dist),
borderColor: "rgba(216, 138, 138, 1)",
borderWidth: 0.5,
label: {
content: "AVERAGE",
fontFamily:'Ubuntu',
enabled: true,
position: "middle",
fontSize: 8,
backgroundColor: 'rgba(0,0,0,0.5)',
}
}
]
}
},
});
//end graph 5//
//graph 6 //
var mainGraphLine4 = new Chart(ctx6, {
type: 'line',
data: {
labels: behav_label,
datasets: [{
data:behav_dist,
backgroundColor: 'rgba(102, 187, 158, 0.2)',
}]
},
options: {
legend: {
position: 'top',
display: false
},
responsive:true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {autoSkip: false,
beginAtZero: true,
}
}],
yAxes: [{
ticks: {min: 0, max:100}
}],
},
annotation: {
annotations: [
{
type: "line",
mode: "horizontal",
scaleID: "y-axis-0",
value: getAvg(behav_dist),
borderColor: "rgba(216, 138, 138, 0.8)",
borderWidth: 0.5,
label: {
content: "AVERAGE",
fontFamily:'Ubuntu',
enabled: true,
position: "middle",
fontSize: 8,
backgroundColor: 'rgba(0,0,0,0.5)',
}
}
]
}
},
});
//end graph 6//
}
})
</script>
You can test you django api using postman. You will get the execution time there.
Also if you want to profile your django app you can refer the following link profiling django

Resources