im stuck with a code.
on my mvc application, i had a view, the view contains a dropdownlist, and a bar chart from charts.js nugget. the datasources of the chart are the model.field1, and model.field2 for each axis,
so, im trying, to, when i change dropdownlist item my model change , im passing the dropdownlist.val() to
an action in the controller, that action change the model, the model returns chaged to the view and the chart must change dinamicly, i post my code, dont know what i doing wrong, but dont work. debuggin i find that the value of the dropdown is passing to the action, but i dont know why the chart dont change.
my view
#model GestorBd.Models.FuenteDatos
<br /><br />
<div>
#Html.DropDownList("TiposAFT", null, "--Opciones--", htmlAttributes: new { #class = "form-control", #onchange = "CargarPartial()" })
</div>
<div style="width:800px; height: 1600px; ">
<canvas id="myChart" ></canvas>
</div>
#section Scripts{
<script>
function CargarPartial() {
var desc = $('#TiposAFT').val();
$.ajax({
url: '/Estadisticas/Index',
type: "POST",
data: JSON.stringify({ param: desc }),
contentType: 'application/json',
success: function (data) {
}
});
}
</script>
<script src="~/Scripts/Chart.js"></script>
<script>
var arregloarea = #Html.Raw(System.Web.Helpers.Json.Encode(Model.Area.ToArray()));
var arregloCantidad = #Html.Raw(System.Web.Helpers.Json.Encode(Model.Cantidad.ToArray()));
var label = #Html.Raw(System.Web.Helpers.Json.Encode(Model.label));
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: arregloarea,
datasets: [{
label: label,
data: arregloCantidad,
backgroundColor: [
'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)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
}
my action
public ActionResult Index(string param)
{
FuenteDatos nuevo = new FuenteDatos();
if(string.IsNullOrEmpty(param))
{ param = "Computadora"; }
nuevo = nuevo.ObjetenerDatosDescripcion(param);
Listados a = new Listados();
ViewBag.TiposAFT = a.TiposAFT();
return View(nuevo);
}
Related
I am facing an issue while refreshing the data using the same variable. Every time data get changed in a variable(mydata) but after an update the chart loaded with same data.while click the refresh button chart get reloded but always showing the old chart in chart
<button type="button" onclick="refresh()">Refresh</button>
<canvas id="mychart"></canvas>
<script >
var config = {
type: 'bar',
options: {
scales: {
y: {
beginAtZero: true
}
}
},
};
var myChart=null;
function refresh(){
$.ajax({
url: '/mydata',
method: 'POST',
data: {"user":user},
async: false,
success: function(data) {
mydata = data;
}
})
config.data = {
labels: ["jan","Feb","Mar","Apr","may","june","july"],
datasets:
[{
data: mydata,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 205, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(201, 203, 207, 0.2)'
],
borderColor: [
'rgb(255, 99, 132)',
'rgb(255, 159, 64)',
'rgb(255, 205, 86)',
'rgb(75, 192, 192)',
'rgb(54, 162, 235)',
'rgb(153, 102, 255)',
'rgb(201, 203, 207)'
]
}]
};
ctx = document.getElementById('mychart');
if(myChart == null){
myChart = new Chart(ctx, config);
} else{
myChart.data.datasets[0].data=mydata;
myChart.update();
}
}
</script>
</body>
I'm trying to display a chart in Django with data from database using JSON. When I go to /distancechart I see my data printed. But when it comes to chart I get blank screen, nothing shows. I was using some tutorials from internet and I have no idea what is wrong here...
views.py fragment
def distancechart(request):
labels = []
data = []
queryset = Distance.objects.values('day', 'distance')
for entry in queryset:
labels.append(entry['day'])
data.append(entry['distance'])
return JsonResponse(data={
'labels': labels,
'data': data,
})
distance.html
{% extends 'index.html' %}
{% block content %}
<canvas id="distancechart" width="1000" height="400"></canvas>
<script>
$.get('{% url "distancechart" %}', function(data) {
var ctx = $("#distancechart").get(0).getContext("2d");
new Chart(ctx, {
type: 'bar',
data: {
labels: data.labels,
datasets: [{
label: 'Distance',
data: data.data,
backgroundColor: [
'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)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
</script>
{% endblock %}
I am fairly new to javascript and I cannot get a bar chart to workout. The problem seems to be living in the chart3 data section. I can't figure out how to organize the two statements to get the proper data. I have literally tried everything to be able to display the two values next to each others in bars but nothing seems to be able to make it. Anybody spots what I am wrong here?
DATA:
{'supplier : "ARAGON", average_service_level_implied:-9.24, average_service_level_optimal: 0.495}
view.py
#method_decorator(login_required, name='dispatch')
class SupplierPage(LoginRequiredMixin,APIView):
def get(self, request, *args, **kwargs):
query = request.GET.get('search_ress', None)
context = {}
if query and request.method == 'GET':
Supplier = supplier.objects.filter(supplier = query)
context.update({'Supplier': Supplier})
return render(request, 'Supplier.html',context)
and chart.js graph
<script>
$(document).ready(function() {
var endpoint = 'items.html'
var forecastdata = []
var reference = []
;
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
reference = data.reference
forecastdata = data.forecastdata
setChart()
},
error: function (error_data) {
console.log(error_data)
}
}
)
function setChart() {
var ctx = document.getElementById('myChart3').getContext('2d');
var myChart3 = new Chart(ctx3, {
type: 'bar',
data: {
labels: ["actual service level", "optimal service level"],
datasets: [{
label: 'Service level analytics',
data: [
{% for dr in reference %}{{ dr.niveau_service_implicite}}, {% endfor %},
{% for dr in reference %}{{ dr.niveau_service_optimal}}, {% endfor %}
],
backgroundColor: [
'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)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
options: {
scales: {
type: 'linear',
position: 'bottom',
xAxes: [{maxBarThickness: 10}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
})
Can try passing the 2 values of the bar with the setChart() function , like this :
function setChart(d1,d2) {
...
data [ d1 , d2 ]
And the extraction of the value can be done while calling the function :
reference = data.reference
forecastdata = data.forecastdata
d1 = ...
d2 = ...
setChart(d1,d2)
This chart shows correctly like so:
But this one does not display the bar:
It displays this line as incorrect where default2 is:
Unresolved variable default2
EDIT
I have commented down below for you to see and added a picture where this error displays:
EDIT
How do I make the chart above appear with bar like the other one?
Been doing these for days and hours and looked for answers here with no luck. Hopefully you can see where I went wrong.
Newbie to this so I appreciate all your help, folks!
EDIT
EDIT
chart.js
var endpoint = '/api/chart/data/';
var defaultData = [];
var labels = [];
var defaultData2 = [];
var labels2 = [];
$.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)
}
});
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
labels2 = data.labels2;
defaultData2 = data.default2; # default2 displays error/as incorrect???
setChart2()
},
error: function (error_data) {
console.log("error");
console.log(error_data)
}
});
function setChart2(){
var ctx = document.getElementById("myChart5");
var myChart5 = new Chart(ctx, {
type: 'bar',
data: {
labels2: labels2,
datasets: [{
label: 'Total',
data: defaultData2,
backgroundColor: [
'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)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});}
function setChart(){
var ctx = document.getElementById("myChart1");
var myChart1 = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Total',
data: defaultData,
backgroundColor: [
'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)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});
views.py
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.contrib.auth import get_user_model
from SiO.member.models import Member
from SiO.CoAdmin.models import Administrator
from rest_framework.views import APIView
from rest_framework.response import Response
import datetime
User = get_user_model()
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'chart/ChartView.html', {})
class ChartViewMonth(View):
def get(self, request, *args, **kwargs):
return render(request, 'chart/ChartView/month.html', {})
class ChartData(APIView):
def get(self, request, format=None):
today = datetime.date.today()
qs_count = Administrator.objects.filter(association=self.request.user.association).count()
qs_count1 = Member.objects.filter(association=self.request.user.association).count()
qs_count2 = Member.objects.filter(reg_date__year=today.year,
reg_date__month=today.month).filter(
association=self.request.user.association).count()
labels2 = ["January"]
default_items2 = [qs_count2, ]
labels = ["Board", "Members"]
default_items = [qs_count, qs_count1]
data = {
"labels": labels,
"default": default_items,
"labels2": labels2,
"default2": default_items2,
}
return Response(data)
urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth import get_user_model
User = get_user_model()
urlpatterns = [
url(r'^ChartView/$', views.ChartView.as_view(), name='ChartView'),
url(r'^ChartView/month$', views.ChartViewMonth.as_view(), name='ChartView/month'),
url(r'^api/chart/data/$', views.ChartData.as_view()),
]
in this code, I was able to get the data from database in the JSON format. now iam struggling to draw a chart in JS with columns as values and rows as time stamp. i have a controller(chartController) that goes into the database and extract the desired data and change it into JSON format, that is values and timestamp. then i created a route for this controller, Route::get('json/{notification_id}','ChartController#speedHistory')->name('speedhistory')
i hava a js class as follows,
document.addEventListener('DOMContentLoaded', function() {
$.getJSON("json", function getdata(data) {
console.log(data);
var pageSpeedValues = o_response;
createChartHistory(pageSpeedLabels);
});
function fetchValues(Labels, Values) {
var pageSpeedLabels = Values;
var pageSpeedValues = Labels;
createChartHistory(pageSpeedLabels);
}
// This function allows us to create a chart for the history page
function createChartHistory(pageSpeedLabels, pageSpeedValues) {
var ctx = document.getElementById("pageSpeedHistoryChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: pageSpeedLabels,
datasets: [{
label: 'PageSpeed History',
data: pageSpeedValues,
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(75, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)',
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(32, 206, 86, 0.5)',
'rgba(77, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)'
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
max: 100,
min: 0
}
}]
}
}
});
}
if(document.querySelector('#pageSpeedHistoryChart')) {
getdata();
}
});
I am not getting the data from the controller into the app.js class, any one how get the idea? iam learning js but seems a bit difficult at this point.
here is my chart controller
<?php
namespace App\Http\Controllers;
use App\Notification;
use App\Status;
use Illuminate\Http\Request;
class ChartController extends Controller
{
public function speedHistory($notification_id){
$o_notification = Notification::find(intval($notification_id));
$o_status = Status::where('name','speed')->first();
$o_response = $o_notification->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get()
->transform(function ($item, $key) {
return collect([
'values' => $item->pivot->values,
'created_at' => $item->pivot->created_at->toDateTimeString()
]);
});
return response()->json($o_response);
}
}