Loading Highcharts series from XML using jQuery - javascript

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);
}

Related

How to Stop Chart.js Rendering Over Previous Chart

I've put together some code which allows me to query a MySQL database, return the result and populate a chart.js. The problem being that each time the AJAX code runs the chart is rendered over the previous one. I've read through a few similar stackoverflow queries which are recommending the use of myChart.destroy(); or other solutions but I' struggling to work out where this should be inserted into the following code.
Note that I've simplified the code below for simplicity sake.
Any assistance on how to stop this chart 'ghosting' occuring would be greatly appreciated.
<script type="text/javascript">
jQuery(document).ready( function($) {
var valueCheck;
jQuery('#afl_player_year').on( 'change', function () {
afl_player_year = $('#afl_player_year').val();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
dataType: "json",
data: {
action: 'call_player_chart_data',
afl_player_year: afl_player_year,
},
success:function(output){
var y_data1 = output[0];
var y_data2 = output[1];
var x_time = ............
new Chart(document.getElementById("myChart"), {
type: 'bar',
data: {
labels: x_time,
datasets: [{.........
}, {.........
}]
},
options: {
scales: {.........
yAxes: [{.........},{.........},
}]
}
}
});
}
});
}).change();
});
</script>

Set a default value of an extjs 4.2 combobox using AJAX

I have a an extjs 4.2 combobox that I'm using to display some data. Now I'm trying that based on a condition the combo would display a default value. I managed to return the needed data based on that condition, however I'm failing to set the necessary value in the combobox. How am I supposed to set that specific value?
combo:
var locationStore = Ext.create('Ext.data.Store', {
model: 'model_LOCATION',
proxy: {
type: 'ajax',
url: 'Record?DB=GEO&Table=LOCATION',
reader: {
type: 'xml',
record:'record'
}
},
autoLoad:true
});
var C_LOCATION= Ext.create('Ext.form.ComboBox', {
name : 'C_LOCATION',
id : '${DB}.${Table}.C_LOCATION',
store : locationStore,
queryMode : 'local',
displayField : 'display',
valueField : 'value',
});
AJAX call:
var data;
var code = 111;
data = "CODE ='" + code + "'";
var text;
$.ajax({
type: "POST",
url: "Record?DB=GEO&Table=LOCATION",
dataType: 'xml',
data: {
"Where": data
},
success: function(xml) {
text = xml;
Ext.getCmp('${DB}.GEO.LOCATION').setValue(text);
}
});
Give the combo box a reference in the config section (reference: 'comboBox'). Then call comboBox.setValue(defaultValueGoesHere) in your function where you are getting the specific value. You may need to hunt down the comboBox reference depending where you are.
I guess you will have to parse your XML response. Similar as in your code definition for the locationStore, where you specify the record in the xml response.
Why do you make the second ajax call?
Could you not filter the locationStore based on the CODE value, instead?

jquery Datatables filter rows

Hi I have a DataTables DataTable object which requests json data via an ajax call. Each object inside the json data has a property called state that can be one of a number of values. Ultimately, I'd like to create several (Data)tables, one for each state without having each table request the same data via ajax again and again. For now, I haven't managed to make a single table filter out the rows with incorrect state yet and I'd like to solve this problem first.
The DataTable object defined as follows:
$(document).ready(function () {
var table = $('#example').DataTable({
data: example,
ajax: {
url: "{{ callback_url }}",
dataType: 'json',
dataSrc: '',
},
createdRow: function (row, data, index) {
},
columns: [{
data: "Type"
}, {
data: "State",
}
}]
});
});
I want to filter the data that comes from the ajax call based on a parameter (e.g. "if (row.State == 'new') {...};"). How can I do that? Does datatables have a function that can be passed to filter each row?
I really need several tables which show data from the same ajax callback but in different states (e.g. a "New" table, an "Old" table etc.). How can I do this without requesting the same json data again and again for each table rendered? Ideally I can store the ajax in a variable but with the async process I'm not sure how this will work out.
You can use one ajax and store the data, and than create each datatable.
Example:
$(document).ready(function () {
var data = null;
$.ajax(URL, {
dataType: 'json',
success: function(ajaxData){
data = ajaxData;
newData = data.filter(function(item){ return item.State == "New"});
oldData = data.filter(function(item){ return item.State == "Old"});
var newTable = $('#newTable').DataTable({
data: newData,
});
var oldTable = $('#oldTable').DataTable({
data: newData,
});
}
});
}

Passing SQL results from controller to chart.js

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

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]

Categories