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]
Related
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
i have three files index.html , getData.php and data.json
index.html ->
<script type="text/javascript">
function load() {
var jsonData = $.ajax({
url: "getData.php",
type: "GET",
data: {variable: "loadavg"},
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 800, height: 400});
}
</script>
<ul class="list">
<p>Load average <input id="loadAvg" type="button" value="Enter" onclick="load();" /> </p>
</ul>
getData.php ->
<?php
// It reads a json formatted text file and outputs it.
if(isset($_GET["variable"]) == "loadavg"){
$string = file_get_contents("data.json");
echo $string;
// if this works you should see in console 'graph on cosole'
}
?>
data.json ->
{
"cols": [
{"id":"","label":"HostName","type":"string"},
{"id":"","label":"CPU","type":"number"},
{"id":"","label":"Free Avg memory","type":"number"}
],
"rows": [
{"c":[{"v":"lp10b2vapp01,w10"},{"v":21}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":15}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":73}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":60}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":48}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":40}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":36}]}
]
}
when i click on button i was unable to see the output (Graph) ,Kindly look help me
Thanks in advance
Don't use async: false. It's terribly bad practice as it locks the UI thread making the browser look to the user like it has crashed until the request completes. Instead use the async callbacks which $.ajax provides you to update the UI of the page once the request has finished. Try this:
function load() {
$.ajax({
url: "getData.php",
type: "GET",
data: {
variable: "loadavg"
},
dataType: "json",
success: function(jsonData) {
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.ColumnChart($('#chart_div')[0]);
chart.draw(data, {
width: 800,
height: 400
});
}
});
}
Also note that you need to get the value of the parameter in the PHP code as well as checking it exists:
if (isset($_GET["variable"]) && $_GET["variable"] == "loadavg")
{
// code here...
}
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
I have a functioning PHP page with AJAX call. What Im trying to do now is to get a user input via a text input and then send thet through _GET into ajax. My code looks like this:
<body onload="test()">
<script>
function test () {
var options = {
chart : {
renderTo : 'container',
type : 'spline',
zoomType: 'x',
},
series: [{
name: '',
data: []
}]
};
year = document.form1.year.value;
$.ajax({
url : "data.php?year="+year,
dataType : 'json',
success : function (json) {
options.series[0].name = json['name'];
options.series[0].data = json['data'];
chart = new Highcharts.Chart(options);
},
});
}
</script>
<form name="form1">
<input type="text" name="year" value="2012">
</form>
</body>
Unfortunately for some reason it does not work, although when I alert "year" the value is correct and corresponds to what is inside the text input.
Sorry, never mind, Im an idiot I solved it already... I accidentaly left the value fixed to 2012 - I did that when I was testing it and forgot to delete it.
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);
}