Passing SQL results from controller to chart.js - javascript

Situation
I would like to pass the count of X from my SQL database from my controller to my view where a chart picks up this data and renders it.
What I have done so far
So far I have the controller code. which gets the count from the table and I am trying to pass this figure back to the chart.
public ActionResult currentPopulation()
{
var dests = db.personal_info.Count();
// return Json(dests, JsonRequestBehavior.AllowGet);
return Content(JsonConvert.SerializeObject(dests), "application/json");
}
I also have the chart (code below) from the view
<script>
var barChartData = {
url: '/Home/currentPopulation',//Local
type: "GET",
dataType: "JSON",
labels: ["A", "B", "C"],
datasets: [
{
// url: '/Home/currentPopulation',//Local
// type: "GET",
// dataType: "JSON",
fillColor: "#26B99A", //rgba(220,220,220,0.5)
strokeColor: "#26B99A", //rgba(220,220,220,0.8)
highlightFill: "#36CAAB", //rgba(220,220,220,0.75)
highlightStroke: "#36CAAB", //rgba(220,220,220,1)
data: [51, 30, 40], //this is the hard coded values which the chart loads
//
},
],
}
$(document).ready(function () {
// new Chart($("#canvas_bar").get(0).getContext("2d")).Bar()
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});
});
</script>
Problem
The problem I have is that, I cannot replace the [51,30,40] for the A,B,C values
which is supposed to come from my controller. I am a bit confused as my action "currentPopulation" is not getting called, and i cannot move the link cause according to the code, the data is picked up from barChartData and assign when the new chart is called.
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
Any help would be appreciated.

If you want your controller to be hit you need to make an ajax request. This ajax call should be done on the action which you want the controller to be called. Button click or so on. Start using console.logs to debug your javascript.
If you want this code to be execute on page open, wrap the ajax call in document.ready function.
$.ajax({
type: "POST",
url: "Home/currentPopulation",
//data: jsonData, if you need to post some data to the controller.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var aData = response.d;
console.log(aData);
//build here your **data** as object wanted by Bar. Colors which you want and so on, options could be empty object {}. I think is possible to call bar without options, you need to read the documentation.
var ctx = $("#myChart").get(0).getContext("2d");
var myBarChart = new Chart(ctx).Bar(data, options);
}
function OnErrorCall(response)
{
alert('error');
}
Here I show you little example how to do it. You can just google chart.js with mvc there is a lot of examples. Check if the url is correctly written I think you should remove the / in the begging.
This is just suggestion.
Also if you had the money and this is serious chart project use highcharts.js ! This is the best library which can work totally offline and gives you really good flexibility.
Usefull links:
ChartJS documentation

Related

JSON Data cannot be stored in variable

Im trying to load the content of a JSON File into an variable.
Before, the variable looked something like this:
var Data = {
teams : [
["Team 1", "Team 2"],
["Team 3", "Team 4"]
],
results : [
[[1,2], [3,4]],
[[4,6], [2,1]]
]}
Now I have a JSON File looking something like this:
{"teams":[["Team 1","Team 2"],["Team 3","Team 4"],"results":[[[[1,2],[3,4]],[[4,6],[2,1]]]}
Now I want that the the content of the JSON File is stored in the Data Variable before. I tried it with Ajax which looks like this:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data
},
});
Console.log works perfect, but the Data is not saved in the variable and I'm getting the error: Uncaught ReferenceError: Data is not defined.
I also tried it with var Data = JSON.parse(data), but this doesn't seem to work either.
And now I'm stuck without any clue.
Thanks for help in advance.
I'm not sure what your code looks like after the ajax call, but I'm guessing the the code where you are using Data is after the ajax call. ajax is asynchrounous. That means that your code doesn't wait for it to finish before moving on. Any code that needs to wait until after it's done fetching the data, you can put in the .success function. Also, it's worth noting that success only gets called when the ajax request is successful. If you want to handle errors, you can use .error Something like this should work:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data;
// Anything that needs to use Data would go inside here
},
error: function(err) {
// handle errors
console.error(err);
}
});
// Any code here will not wait until `Data` is defined
// console.log(Data) // error

passing an array of int to MVC controller using ajax javascript

What am I doing wrong here?
I can successfully pass 4 bool params to a controller. Now I want to pass an array of int to my controller but it doesn't work - I've left my working code in the example(commented out) so you can see I'm not changing that much - I think I'm missing something simple (it is 17:44 afterall!!!). I can see the array is populated using the alert(rolesChecked); statement:
var rolesChecked = [];
$('[type="checkbox"].role-checkbox').each(function () {
if (this.checked)
{
rolesChecked.push($(this).val());
}
});
alert(rolesChecked);
//var administrator = $('#cbAdministrator').is(":checked");
//var manager = $('#cbManager').is(":checked");
//var technician = $('#cbTechnician').is(":checked");
//var transcriber = $('#cbTranscriber').is(":checked");
if (rolesChecked.count > 0){//administrator || manager || technician || transcriber) {
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: {
roleIdXXXs: rolesChecked
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
},
success: function (data) {
//do something...
}
});
}
Controller Action:
public string GetFutureHolidays(List<int> roleIdXXXs)//bool includeAdministrator, bool includeManager, bool includeTechnician, bool includeTranscriber)
{
//do something
}
with the old code, the controller action would be hit... with the array, it never gets hit... What am I missing here...
also, I think List<int> roleIdXXXs should be fine, but I also tried List<string>, int[] and string[] in case it isn't!!!
You need to add the traditional: true ajax option to post back an array to the collection
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
cache: false,
data: { roleIdXXXs: rolesChecked },
traditional: true, // add this
success: function (data) {
}
});
Refer also the answer to this question for more detail on what the options does and the form data it generates.
In your if statement, instead of rolesChecked.count, use rolesChecked.length
You can't submit a list like this from Ajax, the quickest fix in the process you are using is to use serialization-desalinization process, you can send it as
roleIdXXXs: JSON.stringify(rolesChecked)
on Action:
public ActionResult GetFutureHolidays(string rolesChecked)
{
var test = new JavaScriptSerializer().Deserialize<List<int>>(rolesChecked);
}
You should use JSON.stringify() on you AJAX call lice this:
data: {
roleIdXXXs: JSON.stringify(rolesChecked)
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
}

CodeIgniter and JSON objects: how to push my data to database?

I have a JS file that manages my data (push the data in my JSON objects, etc), and the classic MVC structure of files from CodeIgniter.
My JS contains my JSON objects that I would like to push in my database. How could I do for it? How can I reach the controller and the model from my JS file? I just can't figure out what is the right process to achieve my goal! And I find nothing similar to my question.
EDIT
The data to push into the database is a part of the entire JSON object.The data to push is, for example: { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 }
In my JS file, I have tried this code:
$("#hexa-btn").on("click", function () {
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: JSONshapes.shapes[0].nodes[0],
cache: false,
success:
function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
And my controller has this function:
function returndata(){
$index = $this->input->post('index');
$x = $this->input->post('x');
$y = $this->input->post('y');
$weight = $this->input->post('weight');
$px = $this->input->post('px');
$py = $this->input->post('py');
$fixed = $this->input->post('fixed'); ;
echo json_encode(array('node'=>$node));
}
I am not sure at all about this function. It seems this is the role of the model to do this job, isn'it?
2nd EDIT So, I tried the solution of #Harish Lalwani, but this time with my array of nodes (not only one). I have the following function in the JavaScript file:
function sendNode(){
var node_url = "/prototype/insert_node";
var data_node = JSON.stringify(JSONshapes.shapes[0].nodes);
$.post(node_url, {'node_data': data_node}, function(data){
console.log(data.index);
});
}
and the following one in the controller (thank to this post):
function insert_node(){
$node_data = $this->input->post('node_data');
$node_data = json_decode($node_data,true);
echo 'Your Data: ' . $node_data[0]['index'];
},
But, when printing the data, I get undefined. The variable data_node is the following (so, is an array):
[{"index":0,"x":50,"y":80,"weight":2,"px":50,"py":80,"fixed":0},{"index":1,"x":189,"y":107,"weight":2,"px":189,"py":107},{"index":2,"x":95,"y":145,"weight":2,"px":95,"py":145}]
Now, I don't know anymore what to do! I find really too few examples. Can anyone put me out of my misery? Thank you very much in advance!!
Trigger this from your Js file. (include jQuery Library)
provide url, post key and value you will receive post parameters at specified URL.
jQuery.post("<URL>", {dataname: datavalue}, function( r ) {
console.log(r);
});
I am also using ajax.
From your Original Post, I see that you have a JSON object. If it is already in object form, there's no need for you to convert it at all. Just assign that JSON to a variable and pass that variable to your ajax data parameter like so:
$("#hexa-btn").on("click", function () {
var json = { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 };
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: json,
success: function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
Using ajax can solve your problem!
$.ajax({
type: "POST",
url: "test.php",
data: yourData,
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have m

JSON output for highcharts

So I have finally managed to get a chart generated, but the problem is that for some reason the data from JSON is not displayed - ie I get a blank chart.
In the chart options I simply have:
series : [{
name: '2000',
data: [],
}]
The AJAX call looks like this:
$.ajax({
url : 'data.php',
datatype : 'json',
success : function (json) {
options.series[0].data = json['data'];
chart = new Highcharts.Chart(options);
},
});
}
And the data.php output looks like this:
{"data":[-1.4,-1.4,-1.3,-1.3,-1.3,-1.3,-1.3,-1.2,-1.3,-1.2,-1.2,-1.2]}
Im becoming desperate as I tried everything and still get just a blank chart with no data.
If you're using Internet Explorer, those extra commas will cause you problems.
series : [{
name: '2000',
data: []
}]
$.ajax({
url : 'data.php',
datatype : 'json',
success : function (json) {
options.series[0].data = json['data'];
chart = new Highcharts.Chart(options);
}
});
}
Its likely that your json values are coming back as strings but highcharts is expecting numbers.
In your data.php try typing your variables before json_encoding them:
array_push($myArray, (float)$value);
return json_encode(myArray);
If your highcharts data looks like:
["-1.4","-1.4","-1.3","-1.3","-1.3","-1.3","-1.3","-1.2","-1.3","-1.2","-1.2","-1.2"]
It wont render, it needs to be straight number:
[-1.4,-1.4,-1.3,-1.3,-1.3,-1.3,-1.3,-1.2,-1.3,-1.2,-1.2,-1.2]

Loading Highcharts series from XML using jQuery

I am trying to populate a highchart series from an xml source using jQuery. The XML file is an export from RRDTool and has the following format:
<data>
<row><t>1347559200</t><v>2.1600000000e+01</v></row>
<row><t>1347562800</t><v>2.1504694630e+01</v></row>
<row><t>1347566400</t><v>2.1278633024e+01</v></row>
.
.
.
</data>
My approach was to load the data using jQuery and push the series to the chart:
$.ajax({
type: "GET",
url: "data/data.xml",
dataType: "xml",
success: function(xml) {
var series = { data: []
};
$(xml).find("row").each(function()
{
var t = parseInt($(this).find("t").text())*1000
var v = parseFloat($(this).find("v").text())
series.data.push([t,v]);
});
options.series.push(series);
}
});
I end up getting the following error:
Unexpected value NaN parsing y attribute
I created a JSFiddle to demonstrate the code: http://jsfiddle.net/GN56f/
Aside from the cross-domain issue, the error is due to there being an existing empty series in the plot options. The initial series in the options should be set to:
series: []
instead of:
series: [{
name: 'Temperature',
data: []
}]
The subsequent call to options.series.push(series); merely adds a new series leaving the empty one unchanged.
Problems:
you forgot var before declare options and chart
forgot ; after end options
Hava you tried to log options before pass to Highcharts ? You're passing the following series.
That's the expected result ? I think no.
series: [{
name: 'Temperature',
data: []
}, {
data: [// data from xml]
}]
You're creating the chart before complete the request, so options.series.data.push will not work, you have to use setData to update dynamically, but there's a problem, you don't know how long the request you take, so I suggest you to create the chart inside the success.
Try the following.
success: function(xml) {
$('row', xml).each(function() {
options.series.data.push([t,v]);
});
//#todo: declare chart as global before the ajax function
chart = new Highcharts.Chart(options);
}

Categories