Trying to access controller in JavaScript - javascript

My ultimate goal is to use information from my database to create a line graph using my MVC application. So far I have managed to gather this data using a view model and LINQ queries in my controller and I have made sure the data is accurate by running a test in the view. However, I'm having a hard time figuring out how to include it in my JavaScript file. In my controller I have a function
private DataBase db = new DataBase();
public ActionResult GetInfo() {
var model = new UserViewModel();
model.val1=db.table.Where(n=>n.UserID==curUser).Select(n=>n.SomeData).ToArray();
model.val2=db.table.Where(n=>n.UserID==curUser).Select(n=>n.MoreData).ToArray();
model.dictionary = the stuff from above;
And then in my JavaScript file I'm using Chart.Js to graph a chart. So far it just has fake data to make sure everything was linked up correctly but it looks like this:
jQuery(document).ready(function() {
var chart=new CanvasJS.Chart("moodgraph",{
animationEnabled: false,
theme: "light2",
title: {
text: "Simple Line Chart"
},
axisY: {
includeZero: false
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: [
{ x: 1,y: 450 },
{ y: 414 },
{ y: 520,indexLabel: "\u2191 highest",markerColor: "red",markerType: "triangle" },
{ y: 460 },
{ y: 450 },
{ y: 500 },
{ y: 480 },
{ y: 480 },
{ y: 410,indexLabel: "\u2193 lowest",markerColor: "DarkSlateGrey",markerType: "cross" },
{ y: 500 },
{ y: 480 },
{ y: 510 }
]
}]
});
chart.render();
});
That graph does appear in my view so I know all that is working fine. What I've been struggling with is figuring out how to get that dataPoints to populate with the dictionary values that I grabbed in my controller... So far I tried using
var model=#Model.Dictionary
to access the information but that threw an error. And then I've struggled with trying to return an object in the controller but that messes with code that I can't touch as someone else wrote it for this project. I know I'm missing one simple piece but my Google searches don't show me how to do this in the strict parameters I'm stuck with in this project.
How do I access the view model data in my separate JavaScript file?

you can use this :
1 - In your controller :
*
*
ViewBag.Dico = model.dictionary;
return View("chartPage");
2 - in your chartPage.cshtml (or declare your variable globally 'Layout.cshtml'):
<script>
var myPoints= #Html.Raw(Json.Encode(ViewBag.Dico));
</script>
3 - in ChartJs:
jQuery(document).ready(function() {
var chart=new CanvasJS.Chart("moodgraph",{
*
*
*
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: (typeof(myPoints) != "undefined" ? myPoints: [])
}]
});
chart.render();
});

using Chart.JS library you can make dynamic charts from the database data by following the next steps
Model:
suppose you have model for graph data as following:
public class JsResultChart
{
public string Name { get; set; }
public double Value { get; set; }
}
Controller:
return your data from the controller (using model, viewbag..etc) as list
var JsResultChart= new List<JsResultChart>
{
new JsResultChart{ Name ="first", Value = 100 }, //data will be fetched from db
new JsResultChart{ Name ="second", Value = 200 },
};
Model.JsResultChart = JsResultChart;
View:
add something like this:
<div class="row">
<div class="col-md-12">
<input type="hidden" id="Lables" name="Lables" value="#Json.Encode(Model.ChartData.Select(x => x.Name).ToList())" />
<input type="hidden" id="Values" name="Values" value="#Json.Encode(Model.ChartData.Select(x => x.Value).ToList())">
<canvas id="myChart" style="margin: 0 auto;" class="NotPrintable"></canvas>
<div id="ResultsDiv"></div>
</div>
</div>
javascript:
var Names = $("#Lavels").val();
var Numbers = $("#Values").val();
Names = JSON.parse(Names);
Numbers = JSON.parse(Numbers);
var data = {
labels: Names,
datasets: [{
fill: false,
data: Numbers,
label: "Value" //you can write(label: Names) rather than (label: "Value")
}]
};
var ctx = $("#myChart");
var barChart = new Chart(ctx, {
type: 'line',
data: data,
options: options //add your options
});

Related

How to put function in ChartJS data structures?

I'm making a website with one graph that use ChartJS library. This chart display, on the website, all of the data available as default.
My goal is to let the visitors to choose a different number of data of the graph. So, I did one button at the top of the chart which, when a visitor click on it, must change the number of data displayed.
The problem is that ChartJS use a JSON object and I not succeed configure different behaviors in it.
...
datasets: [
{
label: "Exemple",
data: [
{ x: "Day1", y: 0 },
{ x: "Day2", y: 1 },
{ x: "Day3", y: 2 },
{ x: "Day4", y: 3 },
{ x: "Day5", y: 4 },
....
],
...
I tried to put an event on it, like :
data: mybutton.addEventListener("click", () => {
[{x: "Day1", y: 0}]
},
A function, like :
data: myFunction(),
Even a variable with function into, like :
const myData = () => {
// function
}
data: myData,
Or an If else.
Nothing worked... Do you any idea ?
I found the solution by myself.
I put the JSON object in a function, put an AddEventListener("click", function()), targeted the part of the JSON to modify and added an update() at the end.
function chartFunction() {
....
// data before
datasets: [
{
label: "Exemple",
data: [
{ x: "Day1", y: 0 },
.....
button.addEventListener("click", () => {
(myChart.data.datasets[0].data = [...]).myChart.update();
});
};
chartFunction();

Duplicated Series of Data in Google Area Chart

I'm trying to plot a Chart using Google's Visualization API using some data returned from a database by a PHP script. My data is a JSON object in the format:
jsonObject = {
"routes":[{
"name":"Route 0",
"chart":{
"x":[ /* array of x values */ ],
"y":[ /* array of y values */ ]
}
},{
"name":"Route 1",
"chart":{
"x":[ /* array of x values */ ],
"y":[ /* array of y values */ ]
}
}]};
I'm trying to plot a chart of each member of jsonObject.routes individually using the following code:
function drawChart() {
var baseChart = jsonObject.routes[1].chart; // Want to manipulate this value to plot different sets of data
var chartData = [];
for (var g = 0; g < baseChart.x.length; g++) {
var dataPoint = {
c: [
{ v: baseChart.x[g] },
{ v: baseChart.y[g] },
]
};
chartData.push(dataPoint);
}
var dataJson = {
cols: [
{ role: "domain", type: "number", label: "Distance" },
{ role: "data", type: "number", label: "Main Route" },
],
rows: chartData
};
var dataTable = new google.visualization.DataTable(dataJson);
var chart = new google.visualization.AreaChart(document.getElementById('chart'));
var options = {};
chart.draw(dataTable, options);
}
However, whenever I try to access the latter objects of the jsonObject.route array, it seems to be pulling data for every object in the jsonObject.route array prior to it as well.
I've included a link to a Fiddle with a sample dataset at the bottom; the chart is fine when only plotting jsonObject.routes[0], but when trying to plot jsonObject.routes[1] it will plot the data from jsonObject.routes[0] too.
I suspect this is more of an issue with my Javascript code rather than with the Google Visualization API, but I've been pulling my hair out with it and can figure out why it's pulling data from all the elements in that array. Many thanks for any help!
Link to Fiddle
not sure i completely follow the question...
looking at the fiddle, the one chart seems to draw fine,
just need to sort the data to fix funny looking area
dataTable.sort([{column: 0}]);
see following snippet in order to draw separate charts for each --> jsonObject.routes
google.charts.load('current', {
callback: function () {
jsonObject.routes.forEach(function (route) {
var chartData = [];
route.chart.dist.forEach(function (x, index) {
chartData.push({
c: [
{v: x},
{v: route.chart.ele[index]}
]
});
});
var dataJson = {
cols: [
{ role: "domain", type: "number", label: "Distance" },
{ role: "data", type: "number", label: "Main Route" },
],
rows: chartData
};
var dataTable = new google.visualization.DataTable(dataJson);
dataTable.sort([{column: 0}]);
var options = {};
var container = document.getElementById('chart_div').appendChild(document.createElement('div'));
var chart = new google.visualization.AreaChart(container);
chart.draw(dataTable, options);
});
},
packages:['corechart']
});
note: definition of jsonObject is excluded above
AND
when building a working fiddle, i noticed that since jsonObject is so large,
once you leave the page and comeback,
the fiddle breaks it up into chunks, which then breaks the code
and only one chart is drawn
here is a working fiddle with far less data

take an array of objects and put it in a bar graph

i am a new when it comes to jquery and javascript but I'm trying learn slowly.What my question is, if i have a json file that looks like
var data= [{"tasknumber":304030,
"date":"2012-05-05",
"operator":"john doe"},
{"tasknumber":23130,
"date":"2012-07-07",
"operator":"john doeeeeeeee"},
{"tasknumber":233330,
"date":"2012-08-08",
"operator":"john doe"}]
and i applied .countBy to it from the underscore library to get a array that looks like this
{"john doe":2,"john doeeeeeeee":1}
so for the next part im using a sample jquery graph outline which i found online
<!DOCTYPE HTML>
<html>
<head>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
I tried a couple ways to call my new array within this part of the code
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
//insert here
]
}
]
but i only get blank screens and undefine when i try and open it.does anyone have any guidance for me on how to call my array within the datapoints?
my data is in a different file called task.json and i gotta call it using
var input=require('./task.json');
const _ = require(`underscore`);
var names=_.countBy(input,'operator');
Lets say, your JSON object is stored in some variable(eg: myObject).
var myObject = {"john doe":2,"john doeeeeeeee":1};
Declare a variable to store dataPoints from your JSON and push dataPoints into your array.
var dps = [];
for(var element in myObject) {
dps.push({label: element, y: myObject[element]});
}
Once you have done this, assign this variable (dps) to dataPoints of CanvasJS chart.
data: [
type: "column",
dataPoints: dps
]
You can see a working example in this fiddle.

Getting JSON from Google for Highmaps

I'm pretty rusty with JavaScript, so I'm hoping someone can help me out. I'm working with Highmaps and would like to link the map to data in a Google Spreadsheet. (It's a U.S. map of counties which will be updated regularly, so having it all in the script itself is a little unwieldy.)
This is what my code looks like now:
<script type="text/javascript">
var example = 'us-counties',
theme = 'default';
(function($) { // encapsulate jQuery
$(function() {
var data = [{
"code": "us-al-001",
"name": "Autauga County, AL",
"value": 0
},
…
{
"code": "us-pr-153",
"name": "Yauco Municipio, PR",
"value": 0
}],
countiesMap = Highcharts.geojson(Highcharts.maps['countries/us/us-all-all']),
lines = Highcharts.geojson(Highcharts.maps['countries/us/us-all-all'], 'mapline'),
options;
// Add state acronym for tooltip
Highcharts.each(countiesMap, function(mapPoint) {
mapPoint.name = mapPoint.name + ' County, ' + mapPoint.properties['hc-key'].substr(3, 2);
});
series: [{
name: 'County',
mapData: countiesMap,
data: data,
joinBy: ['hc-key', 'code'],
tooltip: {
enabled: true,
positioner: function () {
return { x: 0, y: 250 };
},
pointFormat: '{point.name}',
borders: 0.5
},
borderWidth: 0.5
}, {
type: 'mapline',
name: 'State borders',
data: [lines[0]],
color: 'white'
}, {
type: 'mapline',
name: 'Separator',
data: [lines[1]],
color: 'gray'
}]
};
// Instanciate the map
$('#container').highcharts('Map', options);
});
$(document).ready(function() {
$("#view-menu").click(function(e) {
$("#wrap").toggleClass("toggled");
});
$("#sidebar-close").click(function(e) {
$("#wrap").removeClass("toggled");
});
});
})(jQuery);
</script>
Of course, since there's over 3,200 counties, I'd rather store that data elsewhere and pull it into the var data = [] string, but I'm not sure how to do that.
Any help would be appreciated.
Although this isn't something I've done, it looks like this should be relatively straightforward to do (although nothing is as simple as it looks of course).
There is an API for Google Sheets (https://developers.google.com/google-apps/spreadsheets/) and you can Google examples of how to retrieve data - this one looks clear (https://developers.google.com/gdata/docs/json) although it does point out that there are newer versions of some of the relevant APIs.
If you pull in the JSON data from the Google Sheet you then just need to put the values into the 'value' element of your data variable. You could do all of that within your main function or do it separately and pass it to your function as a parameter.

Highcharts not plotting Date string as Category

I am using Highcharts to plot JSON Data. The dates are in the string format.
JSON Data:
[{"BRENT_SPOT":70.88,"TRADE_DATE":"31-JUL-2009"},{"BRENT_SPOT":73.28,"TRADE_DATE":"03-AUG-2009"},{"BRENT_SPOT":74.31,"TRADE_DATE":"04-AUG-2009"},{"BRENT_SPOT":74.96,"TRADE_DATE":"05-AUG-2009"},{"BRENT_SPOT":74.4,"TRADE_DATE":"06-AUG-2009"},{"BRENT_SPOT":72.84,"TRADE_DATE":"07-AUG-2009"},{"BRENT_SPOT":73.29,"TRADE_DATE":"10-AUG-2009"},{"BRENT_SPOT":72.04,"TRADE_DATE":"11-AUG-2009"}]
HighCharts / JQuery Code :
<script>
var chart;
$(function() {
var options = {
chart: {
renderTo: 'container',
zoomType: 'xy',
type: 'line'
},
title: {
text: 'Brent Daily Price Curve (FPC as at <cfoutput>#f_date#</cfoutput>)'
},
xAxis: {
labels: {
rotation: 45,
step: 3
},
type: 'category'
},
yAxis: {
lineWidth: 1,
title: {
text: '$ USD'
},
min: 0
},
series: []
};
$.getJSON("brentpricehc_test.cfm?f_date=<cfoutput>#f_date#</cfoutput>", {}, function(jsonResult) {
var BrentUSDPrice = {
name: "Brent Spot (USD)",
type: "line",
data: [],
marker: {
radius: 2
}
};
$(jsonResult).each(function(index) {
BrentUSDPrice.data.push([this.TRADE_DATE, this.BRENT_SPOT]);
});
/*options.series[0] = BrentUSDPrice;*/
options.series.push(BrentUSDPrice);
chart = new Highcharts.Chart(options);
});
});
</script>
I'm unable to plot any values wrt each of the date strings. I tried converting the JSON dates to datetime instead but still the same issue.
Few More details (for testing purposes):
Modifying to the below line plots the graph with the correct "brent_spot" values. This means that the issue lies with the way the "trade_dates" are 'not' plotting.
BrentUSDPrice.data.push([index, this.BRENT_SPOT]);
Edit 2 : (Using Datetime type to make the code work)
JSON Data (New): Returned as TO_CHAR(TRADE_DATE, 'YYYY/MM/DD')
[{"BRENT_SPOT":70.88,"TRADE_DATE":"2009\/07\/31"},{"BRENT_SPOT":73.28,"TRADE_DATE":"2009\/08\/03"},{"BRENT_SPOT":74.31,"TRADE_DATE":"2009\/08\/04"},{"BRENT_SPOT":74.96,"TRADE_DATE":"2009\/08\/05"},{"BRENT_SPOT":74.4,"TRADE_DATE":"2009\/08\/06"},{"BRENT_SPOT":72.84,"TRADE_DATE":"2009\/08\/07"},{"BRENT_SPOT":73.29,"TRADE_DATE":"2009\/08\/10"},{"BRENT_SPOT":72.04,"TRADE_DATE":"2009\/08\/11"}]
$(jsonResult).each(function(index) {
BrentUSDPrice.data.push([new Date(this.TRADE_DATE), this.BRENT_SPOT]);
});
Server side language used : Coldfusion
Database : Oracle
Am I doing something silly somewhere?
I have just tried your code, and it works perfectly fine, see: http://jsfiddle.net/3bQne/1026/
I guess, you need to update to Highcharts 3.0.10 to get this working.
If you are using type: 'category' then you need to assign name: to the data points. See the categories entry at http://api.highcharts.com/highcharts#xAxis
If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highcharts 3.0, categories can also be extracted by giving each point a name and setting axis type to "category".
So the question is whether you are using Highcharts 3.0 and if you do then it needs to look something like this:
data: [{
name: 'Point 1',
color: '#00FF00',
y: 0
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
see: http://api.highcharts.com/highcharts#series.data

Categories

Resources