why do other charts on my webpage are not showing eventho there is no syntax error in PhP and charts.js? - chart.js

I made a dashboard on my website that has 3 different visualization charts, the data is from my database, and the problem that I'm encountering is that the other two are not showing eventhough the first one shows itself. moreover, if I hide or remove the first chart, the second one appears, but the third one still doesn't show. refer to images below:
First Chart Shows the following two are not.
The second chart only shows itself when I delete the code of the first chart.
The 3rd chart is the same case as 2nd, needed to remove the first and second charts just to see the third one.
here is my code:
<!--CHARTS-->
<!--BAR CHART-->
<div class="container-fluid px-4">
<?php
// Attempt select query execution
try{
$barsql = "SELECT * FROM castro_rentals.unit";
$barresult = $pdo->query($barsql);
if($barresult->rowCount() > 0) {
$price = array();
$unit_no = array();
while($row = $barresult->fetch()) {
$price[] = $row["price"];
$unit_no[] = $row["unit_no"];
}
unset($barresult);
} else {
echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $barsql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
<div class="card mb-4">
<!--BAR CHART-->
<div class="card-header">
<i class="fas fa-chart-bar me-1"></i>
Unit Prices
</div>
<div class="card-body">
<canvas id="myBarChart" width="100%" height="50"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//SETUP BLOCK
const price = <?php echo json_encode($price); ?>;
const unit_no = <?php echo json_encode($unit_no); ?>;
const data = {
labels: unit_no,
datasets: [{
label: 'Price',
data: price,
backgroundColor: ['rgba(57, 43, 90, .6)'],
borderColor:'rgb(57, 43, 90)',
borderWidth: 2
}]
};
//CONFIG BLOCK
const config = {
type: 'bar',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
//RENDER BLOCK
const myBarChart = new Chart(
document.getElementById('myBarChart'),
config
);
</script>
<div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
</div>
<div class="row">
<div class="col-lg-6">
<!--LINE CHART-->
<?php
include('config/dbcon.php');
// Attempt select query execution
try{
$linesql = "SELECT * FROM castro_rentals.payment";
$lineresult = $pdo->query($linesql);
if($lineresult->rowCount() > 0) {
$amount = array();
$paymentdate = array();
while($row = $lineresult->fetch()) {
$amount[] = $row["amount"];
$paymentdate[] = $row["paymentdate"];
}
unset($lineresult);
} else {
echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $linesql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-chart-line me-1"></i>
Monthly Income
</div>
<div class="card-body">
<canvas id="myLineChart" width="100%" height="50"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//SETUP BLOCK
const amount = <?php echo json_encode($amount); ?>;
const paymentdate = <?php echo json_encode($paymentdate); ?>;
const data = {
labels: paymentdate,
datasets: [{
label: 'Amount',
data: amount,
backgroundColor: ['rgba(57, 43, 90, .6)'],
borderColor:'rgb(57, 43, 90)',
borderWidth: 2
}]
};
//CONFIG BLOCK
const config = {
type: 'line',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
//RENDER BLOCK
const myLineChart = new Chart(
document.getElementById('myLineChart'),
config
);
</script>
<div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
</div>
</div>
<!--PIE CHART-->
<div class="col-lg-6">
<!--PIE CHART-->
<?php
include('config/dbcon.php');
// Attempt select query execution
try{
$piesql = "SELECT * FROM castro_rentals.property";
$pieresult = $pdo->query($piesql);
if($pieresult->rowCount() > 0) {
$propertyname = array();
$paymentdate = array();
while($row = $pieresult->fetch()) {
$propertyname[] = $row["propertyname"];
$propertytype[] = $row["propertytype"];
}
unset($pieresult);
} else {
echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $piesql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-chart-pie me-1"></i>
# of Property Type
</div>
<div class="card-body">
<canvas id="myPieChart" width="100%" height="50"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//SETUP BLOCK
const propertyname = <?php echo json_encode($propertyname); ?>;
const propertytype = <?php echo json_encode($propertytype); ?>;
const data = {
labels: propertytype,
datasets: [{
label: 'propertyname',
data: propertyname,
backgroundColor: ['rgba(57, 43, 90, .6)'],
borderColor:'rgb(57, 43, 90)',
borderWidth: 2
}]
};
//CONFIG BLOCK
const config = {
type: 'pie',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
//RENDER BLOCK
const myPieChart = new Chart(
document.getElementById('myPieChart'),
config
);
</script>
<div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
</div>
</div>
</div>
The only thing I tried to do is to play with the <div> before the <canvas> I thought it wouldn't show because of spacing and size problems but I tried modifying, removing, resizing them, it still didn't show.

Related

Vue.js - Vuetify - Hard time to test a menu component

Given the following Toolbar component, I am trying to test the locale changing upon click on menu item ... but the wrapper content is not changing after a mouseover event on the menu selector ...
Toolbar.vue
<template>
<v-toolbar height="80px" fixed>
<v-toolbar-title>
<img src="#/assets/images/app_logo.png" alt="">
<v-menu bottom offset-y open-on-hover class="btn btn--flat" style="margin-bottom: 12px;">
<v-btn id="current-flag" flat slot="activator">
<img :src="flagImage(currentLocaleIndex)" width="24px">
</v-btn>
<v-list>
<v-list-tile v-for="(locale, index) in locales" :key="index" #click="switchLocale(index)">
<div class="list__tile__avatar avatar--tile" #click="switchLocale(index)">
<img :src="flagImage(index)" width="24px">
</div>
<div class="list__tile__title" v-html="flagTitle(index)"></div>
</v-list-tile>
</v-list>
</v-menu>
</v-toolbar-title>
<v-spacer></v-spacer>
<v-toolbar-items>
<!-- MENU HOME-->
<v-btn flat #click="$router.push(menuItems.home.link)">
<v-icon left>{{ menuItems.home.icon }}</v-icon>
<span>{{ menuItems.home.title | translate }}</span>
</v-btn>
<!-- ABOUT HOME-->
<v-btn flat #click="$router.push(menuItems.about.link)">
<v-icon left>{{ menuItems.about.icon }}</v-icon>
<span>{{ menuItems.about.title | translate }}</span>
</v-btn>
</v-toolbar-items>
</v-toolbar>
</template>
<script>
// import i18n from '#/locales'
export default {
name: "Toolbar",
props: ["appName"],
data() {
return {
menuItems: {
home: { icon: "home", title: "Home", link: "/" },
about: { icon: "info", title: "About", link: "/about" }
},
locales: [
{ id: "en", title: "English", flag: "#/assets/images/flag_en_24.png" },
{ id: "fr", title: "Français", flag: "#/assets/images/flag_fr_24.png" },
{ id: "br", title: "Português", flag: "#/assets/images/flag_br_24.png" }
]
};
},
computed: {
currentLocaleIndex: function() {
let index = this.locales.findIndex(o => o.id === this.$i18n.locale);
return index;
},
currentLocaleTitle: function() {
let obj = this.locales.find(o => o.id === this.$i18n.locale);
return obj.title;
},
currentLocaleFlag: function() {
let obj = this.locales.find(o => o.id === this.$i18n.locale);
return obj.flag;
}
},
methods: {
flagImage: function(index) {
return require("#/assets/images/flag_" +
this.locales[index].id +
"_24.png");
},
flagTitle: function(index) {
return this.locales[index].title;
},
switchLocale: function(index) {
this.$i18n.locale = this.locales[index].id;
}
},
mounted() {}
};
</script>
Toobar.spec.je
import Vue from "vue";
import router from "#/router";
import Vuetify from "vuetify";
import i18n from "#/locales";
import { mount, shallowMount } from "#vue/test-utils";
import Toolbar from "#/components/shared/Toolbar.vue";
describe("App.vue", () => {
let wrapper;
beforeEach(() => {
Vue.use(Vuetify);
Vue.filter("translate", function(value) {
if (!value) return "";
value = "lang.views.global." + value.toString();
return i18n.t(value);
});
const el = document.createElement('div');
el.setAttribute('data-app', true);
document.body.appendChild(el);
});
it("should change locale", () => {
// given
wrapper = mount(Toolbar, { router, i18n });
console.log('CURRENT LOCALE INDEX: ', wrapper.vm.currentLocaleIndex);
// console.log(wrapper.html());
const currentFlagBtn = wrapper.find("#current-flag");
console.log(currentFlagBtn.html())
currentFlagBtn.trigger('mouseover');
wrapper.vm.$nextTick( () => {
console.log(wrapper.html());
// const localesBtn = wrapper.findAll("btn");
});
// when
// localesBtn.at(1).trigger("click"); // French locale
// then
// expect(wrapper.wrapper.vm.currentLocaleIndex).toBe(1);
});
});
console.log
console.log tests/unit/Toolbar.spec.js:32
CURRENT LOCALE INDEX: 0
console.log tests/unit/Toolbar.spec.js:35
<button type="button" class="v-btn v-btn--flat" id="current-flag"><div class="v-btn__content"><img src="[object Object]" width="24px"></div></button>
console.log tests/unit/Toolbar.spec.js:38
<nav class="v-toolbar v-toolbar--fixed" style="margin-top: 0px; padding-right: 0px; padding-left: 0px; transform: translateY(0px);">
<div class="v-toolbar__content" style="height: 80px;">
<div class="v-toolbar__title">
<img src="#/assets/images/app_logo.png" alt="">
<div class="v-menu btn btn--flat v-menu--inline" style="margin-bottom: 12px;">
<div class="v-menu__activator">
<button type="button" class="v-btn v-btn--flat" id="current-flag">
<div class="v-btn__content">
<img src="[object Object]" width="24px">
</div>
</button>
</div>
</div>
</div>
<div class="spacer"></div>
<div class="v-toolbar__items">
<button type="button" class="v-btn v-btn--flat">
<div class="v-btn__content">
<i aria-hidden="true"class="v-icon v-icon--left material-icons">home</i>
<span>Home</span>
</div>
</button>
<button type="button" class="v-btn v-btn--flat">
<div class="v-btn__content">
<i aria-hidden="true" class="v-icon v-icon--left material-icons">info</i>
<span>About</span>
</div>
</button>
</div>
</div>
</nav>
I found a solution, but maybe someone can explain why :
btnFlags.at(1).vm.$emit('click'); // OK
and
btnFlags.at(1).trigger('click'); // NOT OK
this is the spec which is running fine :
import Vue from "vue";
import router from "#/router";
import Vuetify from "vuetify";
import i18n from "#/locales";
import { mount, shallowMount } from "#vue/test-utils";
import Toolbar from "#/components/shared/Toolbar.vue";
describe("Toolbar.vue", () => {
let wrapper;
beforeEach(() => {
Vue.use(Vuetify);
Vue.filter("translate", function(value) {
if (!value) return "";
value = "lang.views.global." + value.toString();
return i18n.t(value);
});
const el = document.createElement('div');
el.setAttribute('data-app', true);
document.body.appendChild(el);
});
it("should change locale", async () => {
// given
wrapper = shallowMount(Toolbar, { router, i18n });
console.log('CURRENT LOCALE INDEX: ', wrapper.vm.currentLocaleIndex);
const btnFlags = wrapper.findAll("v-list-tile-stub");
// when
btnFlags.at(1).vm.$emit('click');
await wrapper.vm.$nextTick();
// then
console.log('NEW LOCALE INDEX: ', wrapper.vm.currentLocaleIndex);
expect(wrapper.vm.currentLocaleIndex).toBe(1);
});
});

ionic 2 - Using Highchart in the Segment

I use HighChart library in the Segment, my segment have 2 tab DASHBOARD and NEW, my Chart in the DASHBOARD tab. First run: My Chart run, but i click to New tab and come back DASHBOARD tab => My chart not run ?
[sorry, i'm not good english]
-- My code html:
<div class="segment-chart">
<ion-segment [(ngModel)]="pet">
<ion-segment-button value="dashboard" (ionSelect)="selectedFriends()">
DASHBOARD
</ion-segment-button>
<ion-segment-button value="new">
NEW
</ion-segment-button>
</ion-segment>
</div>
<div [ngSwitch]="pet">
<div class="chart" *ngSwitchCase="'dashboard'">
<!--View Chart-->
<div #chart>
<chart type="StockChart" [options]="options"></chart>
</div>
</div>
<ul *ngSwitchCase="'new'" style="list-style-type:none" class="div-new-body">
<li class="div-new-li" *ngFor="let new of lsNews">
<div class="div-new-detail">
<div class="div-new-title">
{{new.date}}
</div>
<div class="div-new-content">
{{new.title}}
</div>
</div>
<div class="div-new-nav">></div>
</li>
</ul>
</div>
My code file ts:
export class ChartPage implements AfterViewInit, OnDestroy {
private _chart: any;
lastData: any
lstData: any = []
pet : any
lsNews : any = []
opts : any;
#ViewChild('chart') public chartEl: ElementRef;
//chartOption: any
// Destroy Chart
ngOnDestroy(): void {
// throw new Error("Method not implemented.");
console.log("OnDestroy run")
var chart = this._chart
chart.destroy();
}
// option Chart
ngAfterViewInit() {
if (this.chartEl && this.chartEl.nativeElement) {
this.opts.chart = {
// type: 'area',
renderTo: this.chartEl.nativeElement,
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, '#3d4d64'],
[1, '#3d4d64']
]
},
height: '90%',
spacingBottom: 15,
spacingTop: 10,
spacingLeft: 10,
spacingRight: 10,
};
console.log('chart create ss')
this._chart = new Highcharts.StockChart(this.opts);
}
}
constructor(public navCtrl: NavController, public navParams: NavParams, public service: Service) {
const me = this;
this.pet= 'dashboard';
setInterval(function () {
if (me._chart) {
me._chart['series'][0].addPoint([
(new Date()).getTime(), // gia tri truc x
//5// gia tri truc y
me.getData()
],
true,
true);
}
}, 3000);
this.opts = {
credits: {
enabled: false
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
labels: {
style: {
color: '#705f43' // color time
}
},
lineColor: '#705f43' // 2 line cuoi mau trang
},
yAxis: {
gridLineColor: '#705f43', //line gach ngang
labels: {
style: {
color: '#fff'
}
},
lineColor: '#ff0000',
minorGridLineColor: '#ff0000',
tickColor: '#fff',
tickWidth: 1,
title: {
style: {
color: '#ff0000'
}
}
},
navigator: {
enabled: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0,
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -50; i <= 0; i += 1) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
}()),
zones: [{
color: '#f8ad40'
}]
}]
};
//end contructor
}
In case you have not been able to resolve this issue, I had the same issue using ion-segment and I was able to resolve it when I replaced ngSwitch with the [hidden] property.
The problem is that the canvas only get rendered once. The canvas is also lost once you switch between your segments, the only solution is to hide you segment when switching between segments
Edit your HTML code to the one below and you should be okay
<div class="segment-chart">
<ion-segment [(ngModel)]="pet">
<ion-segment-button value="dashboard" (ionSelect)="selectedFriends()">
DASHBOARD
</ion-segment-button>
<ion-segment-button value="new">
NEW
</ion-segment-button>
</ion-segment>
</div>
<div >
<div class="chart" [hidden] = "pet != 'dashboard'">
<!--View Chart-->
<div #chart>
<chart type="StockChart" [options]="options"></chart>
</div>
</div>
<ul [hidden] = "pet != 'new'" style="list-style-type:none" class="div-new-body">
<li class="div-new-li" *ngFor="let new of lsNews">
<div class="div-new-detail">
<div class="div-new-title">
{{new.date}}
</div>
<div class="div-new-content">
{{new.title}}
</div>
</div>
<div class="div-new-nav">></div>
</li>
</ul>
</div>
That should solve the issue.

My Bootstrap Modal is Not hiding after Successful Login,Got Stuck

I got stuck at this javascript code,why it is not working ,I used a static backdrop bootstrap model for login,after successful login ,i want to hide the model in success callback function but the model is not hiding,the Page is still there,don't know what i am doing wrong
enter image description here
Myjs File
$(document).ready(function () {
$('#myModal').modal({
backdrop: 'static',
});
});
function Login() {
var dataobject = { Social_Security_Number: $('#Social_Security_Number').val(), Lumik_Id: $('#Lumik_Id').val() };
// var dataobject = { Social_Security_Number:"123456789", Lumik_Id: "sgupta8" };
$.ajax({
url: '/User/Login',
type: "POST",
data: dataobject,
dataType: "json",
success: function (result) {
if (result.toString == "Success") {
$('#myModal').modal('hide');
//redirecttoPage()
}
},
error: function (result) {
alert('Error');
}
})
}
UserController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using login.Models;
namespace login.Controllers
{
public class UserController : Controller
{
UserBusinessLogic obj = new UserBusinessLogic();
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(User user)
{
string message = "";
if (ModelState.IsValid)
{
if (obj.checkuserlogin(user) > 0)
{
message = "Success";
}
else
{
message = "Username or Password is wrong";
}
}
else {
message = "ALL FIELDS ARE REQUIRED";
}
if (Request.IsAjaxRequest())
{
return Json(message, JsonRequestBehavior.AllowGet);
// return RedirectToAction("Profile", "User", new { #name = result });
}
else
{
return RedirectToAction("Index", "Home");
}
}
public ActionResult Profile(string name)
{
return View();
}
}
}
Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
</head>
#*<script src="../../Scripts/jquery-1.9.1.js"></script>*#
<script src="../../Scripts/jquery-1.9.1.min.js"></script>
<script src="../../Scripts/Myfile.js"></script>
<link href="../../Scripts/bootstrap.min.css" rel="stylesheet" />
<script src="../../Scripts/bootstrap.min.js"></script>
<body>
#RenderBody()
</body>
Login.cshtml
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
</div>
<br />
<div class="form-group">
<label for ="Social_Security_Number" class="col-lg-3 control-label"></label>
<input class="form-control" id="Social_Security_Number" placeholder="Social Security Number" type="text" />
</div>
<div class="form-group">
<label for="Lumik_Id" class="col-lg-3 control-label"></label>
<input class="form-control" id="Lumik_Id" placeholder="Lumik Id" type="text" />
</div>
<div class="modal-footer">
<input type="button" value="Login" class="btn btn-primary" onclick="Login()" />
</div>
</form>
</div>
</div>
</div>
<style>
.modal-dialog {
max-width:480px;
}
.modal-dialog {
transform:translate(0,58%) !important;
-as-transform:translate(0,58%) !important;
-webkit-transform:translate(0,58%) !important;
}
.RbtnMargin {
margin-left:90px;
}
</style>
Could you try : $(document).find('#myModal').modal('hide'); instead of $('#myModal').modal('hide');
Reason is : your data added dynamically.
Let me know.

iOnic list not refreshing after adding a new item to the list using web service

We have a iOnic based project and during check out users can add new address to their account.
This is what my controller file look like
$scope.addAddress = function() {
$scope.showLoading();
addressService.addUserAddress($scope.userDetails.userID, $scope.addAddressdata.houseNo, $scope.addAddressdata.street, $scope.addAddressdata.AddDesc, $scope.addAddressdata.LID)
.success(function(response) {
console.log(response);
$scope.hideLoading();
$scope.closeModal();
$scope.getAllAddress();
});
};
$scope.getAllAddress = function() {
addressService.getAllLocations()
.success(function(response) {
$scope.locations = response;
$scope.hideLoading();
});
};
And this is what my services file look like
function() {
"use strict";
var myApp = angular.module('jobolo');
myApp.service('addressService', ['$http', 'appVariableService', function($http, appVariableService) {
var addressService = this;
addressService.getAllLocations = function() {
var data = {
appid: appVariableService.get('appId')
};
return $http.post(appVariableService.get('baseURL') + 'useraddress/getMyLocation', data);
};
addressService.getUserAddress = function(userId) {
return $http.get(appVariableService.get('baseURL') + 'useraddress/myaddress/' + userId, {cache:false});
};
addressService.addUserAddress = function(userId, houseNo, street, adddesc, lid) {
var data = {
appid: appVariableService.get('appId'),
userid: userId,
houseno: houseNo,
street: street,
adddesc: adddesc,
lid: lid,
};
return $http.post(appVariableService.get('baseURL') + 'useraddress/adAdd' , data);
};
}]);
})();
When I add a new address it does add to the database but isn't showing in list. I tried adding $scope.refreshList(); to the code too. When I log out and come back it does show up. Thank you for your help in advance
View Codes are
<ion-view class="main-content">
<ion-nav-buttons side="secondary">
<button menu-toggle="right" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<div class="bar bar-subheader">
<h2 class="title">Select Address</h2>
</div>
<ion-content class="has-subheader" scroll="true" overflow-scroll="true" style="bottom:57px">
<div class="list">
<ion-radio
ng-model="data.selectedAddress"
ng-value="address"
ng-repeat="address in userAddresses"
class="radio-nowrap"
>
House No. {{address.HouseNo}}, {{address.Street}}, {{address.AddDesc}}, {{address.AreaName}}, {{address.City}}
</ion-radio>
</div>
<!-- <div class="row">
<div class="col location-form">
<button class="button" type="button" ng-click="openModal()">Add New Address</button>
</div>
</div> -->
</ion-content>
<div class="row" style="position: absolute;bottom: 0;padding:0">
<div class="col location-form">
<button class="button" type="button" ng-click="openModal()">Add New Address</button>
</div>
<div class="col location-form">
<button class="button" type="button" ng-disabled="!data.selectedAddress" ng-click="selectAddress(data.selectedAddress)">Select Address</button>
</div>
</div>

Google Chart not display data

I have a problem with Google Chart, Twig ans Symfony. I make an ajax call to a function which send data to the js function drawing chart. I displayed data outside of the chart and it's working well. I also tried to display a chart with data hard-coded in it and it also displays well. It's only when I put datas from my Controller in chart's datatable that it's not working.
I don't show my Controller because it's sending datas correctly.
Here's my code :
Drawing function :
function drawGraphRepNoteOfColle() {
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Notes', 'Nombre'],
{% for r in repartitionsColle %}
[{{ r.note }}, {{ r.nombre }}],
{% endfor %}
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
}
};
var chart = new google.charts.Bar(document.getElementById('graphRepNoteColle'));
chart.draw(data, options);
}
}
Ajax Call :
function rechargerColleStats() {
var groupes = document.getElementsByClassName("filled-in");
var groupesSelected = getSelectedGroupesOf(groupes);
var colleId = document.getElementById('collapside_colle_form_colles').value;
var numAdherent = document.getElementById('numAdherent').value;
var DATA = {groupesSelected: groupesSelected, idColle: colleId, numAdherent: numAdherent};
var request = $.ajax({
type: "POST",
url: "{{ path('paces_statistique_calculstatistique_getstatscolle') }}",
datatype: "html",
data: DATA,
success: function (response) {
document.getElementById("bodyColapColle").innerHTML = response;
drawGraphRepNoteOfColle();
document.getElementById("tableauQ").reload(true);
}
});
}
index.html.twig :
<nav class="top-nav panel-title">Statistiques</nav>
<div class="card-panel hoverable">
// Groupes selected field (checkboxes)
<div id="bodyColapGroupes">
{% include 'PACESStatistiqueBundle:Default:groupesCheckBoxes.html.twig' %}
</div>
// Form to get colleId
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Choix de la colle</legend>
{{ form_start(formColle) }}
{{ form_end(formColle) }}
</fieldset>
</div>
<div class="card-panel hoverable">
Colles
<div id="bodyColapColle">
{% include 'PACESStatistiqueBundle:Default:collapsideColle.html.twig' %}
</div>
</div>
collapsibleColle.html.twig :
<div id="colles">
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Minor </legend>
{% if minor is defined %}
{{ minor }} / {% if typeColle == 'QC' %}{{ nbQc }}{% else %}20{% endif %}
{% endif %}
</fieldset>
<div class="center">
<fieldset id="fieldchartA" style='height:100%; width: 100% ;border: 2px solid deepskyblue;'>
<legend> Chart1</legend>
<div id="graphRepNoteColle"></div>
</fieldset>
</div>
</div>
getStatsColleAction in Controller :
$repartitionsColles=$em->getRepository( RepartitionColle::class )->findBy(['idStatColle'=>$statsColle]);
//on en recupere les données minor, major, medianne
$notes=array();
$nbRepartition = 0;
foreach($repartitionsColles as $repartitionsColle){
$repartition[$nbRepartition]['note'] = $repartitionsColle->getNote();
$repartition[$nbRepartition]['nombre'] = $repartitionsColle->getNombre();
$nbRepartition++;
}
array_multisort(array_column($repartition, 'note'), SORT_ASC, SORT_NUMERIC, $repartition);
Array sent is $repartition. getNote() is a float and getNombre is an integer.
Drawing function and Ajax call are in index.html.twig.
GetStatsColle (function called with AJAX) returns collapsideColle.html.twig with required datas.
Ajax is working : I send other infos with the same call and it is rendered.
i would recommend not relying on google.charts.setOnLoadCallback to draw the chart everytime,
especially if you plan to draw multiple charts, it should only be called once per page
instead, swap the order of things and start with google.chart.load first,
then you can draw the chart directly from the ajax call
you can include the callback in the load statement as well...
try something like...
google.charts.load('current', {
callback: rechargerColleStats,
packages:['bar']
});
function drawGraphRepNoteOfColle() {
var data = google.visualization.arrayToDataTable([
['Notes', 'Nombre'],
{% for r in repartitionsColle %}
[{{ r.note }}, {{ r.nombre }}],
{% endfor %}
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
}
};
var chart = new google.charts.Bar(document.getElementById('graphRepNoteColle'));
chart.draw(data, options);
}
function rechargerColleStats() {
var groupes = document.getElementsByClassName("filled-in");
var groupesSelected = getSelectedGroupesOf(groupes);
var colleId = document.getElementById('collapside_colle_form_colles').value;
var numAdherent = document.getElementById('numAdherent').value;
var DATA = {groupesSelected: groupesSelected, idColle: colleId, numAdherent: numAdherent};
var request = $.ajax({
type: "POST",
url: "{{ path('paces_statistique_calculstatistique_getstatscolle') }}",
datatype: "html",
data: DATA,
success: function (response) {
document.getElementById("bodyColapColle").innerHTML = response;
drawGraphRepNoteOfColle();
document.getElementById("tableauQ").reload(true);
}
});
}