how to get tow series data in highchart guage chart - javascript

I am ajax calling a php script that outputs two data points
[epoch data, cpu]
I would like to be able to create highchart guage chart and display cpu utilization and as a data lable, I like to display the time that I get from the php call.
function request_cpu_Data() {
$.ajax({
url: 'get_cpu.php',
success: function(data) {
var myObj = JSON.parse(data);
var point = cpu_chart.series[0].points[0];
var point1 = cpu_chart.series[1].points[0];
var newVal=myObj[1];
var newVal1=myObj[0];
point.update(newVal);
point1.update(newVal1);
setTimeout(request_cpu_Data, 10000000);
},
cache: false
});
}
my series options are like this:
series: [{
name: 'CPU',
data: [0]
},{
name: 'Date',
data: []
}
]
I am getting this error:
Uncaught TypeError: Cannot call method 'update' of undefined
Is this how you set up the second series?
var point1 = cpu_chart.series[1].points[0];

Your second series contains no data, so your cpu_chart.series[1].points is an empty array.
You must use setData if data.lenght === 0, like this:
var secondSeries = chart.series[1];
if (secondSeries.data.length === 0) {
secondSeries.setData([newValue]);
} else {
secondSeries.points[0].update(newValue);
}
I hope that will help you.

Related

Can't pass data to chart.js graph

I’m trying to pass my data to the graph but it won't work. If I add numbers to it manually like
data: [1,2,3]
Than it works. In my code you'll see that I console.logged my data.weight and data.goal. They appear in the console as they should.
Here's the code:
var endpoint = '/api/data';
var defaultDataW = [];
var defaultDataG = [];
$.ajax({
method: 'GET',
url: endpoint,
success: function(data){
console.log(data.weight);
console.log(data.goal);
defaultDataW = data.weight;
defaultDataG = data.goal;
var graph = document.getElementById("weight-graph");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var dataFirst = {
label: "Your Weight (Kg)",
data: defaultDataW,
lineTension: 0,
fill: false,
borderColor: 'red'
};
var dataSecond = {
label: "Your Goal (Kg)",
data: defaultDataG,
lineTension: 0,
fill: false,
borderColor: 'blue'
};
var DateData = {
labels: [], //Dates will be here
datasets: [dataFirst, dataSecond]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
}
};
var lineChart = new Chart(graph, {
type: 'line',
data: DateData,
options: chartOptions
});
},
error: function(error_data){
console.log("Error");
console.log(error_data);
}
})
})
You are doing most everything right, but you are changing 'type' of the data.....
what you are doing RIGHT
var defaultDataW = [];
This sets the data to an ARRAY.
Though, in the ajax, you are doing this:
defaultDataW = data.weight;
Which, by your other comments, clearly says that 'data.weight' is an INTEGER.
So, when you try to use that (now INTEGER) as data in a Chart
data: defaultDataW,
It doesn't work (and, no surprise......)
Chart.js requires an ARRAY (at minimum) to work - https://www.chartjs.org/docs/master/general/data-structures/
Now, how can you fix this?????
Pretty simple......
In your ajax, change
defaultDataW = data.weight;
To ADD to the ARRAY (instead of replacing the array with an integer....)
defaultDataW.push(data.weight);
In case you add other code later (or for future projects, putting things in a function, etc....), you might want to also learn about a way to CLEAR that array. It doesn't hurt to do it now, though the way your code is it really should not be needed. I'm including it here for others to reference, etc.
Before doing a 'push' (certainly if you are doing a loop, etc.), you may need to clear the array first, like this:
defaultDataW.length = 0;
This will empty the array and then you can 'push' what you really want in there. If the array is not empty and you push, then you will have the old data as well as the new (of course, depending on what you are doing, that may be a good thing - though in this case, it is not)

How to send data from jquery to javascript

<script>
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
alert("state data"+data);
});
</script>
I have the value in data and want to show in javascript given below.
The fields data is given want to push my state data there.
<script>
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
</script>
Both are written in diffrent script
datasets is an array with an object on index 0. So to define or redeclare the data property in there the syntax is
salesChartData.datasets[0].data = data;
Use it in your callback function:
function(data) {
salesChartData.datasets[0].data = data;
});
Not sure if I understand correctly, is this what you need?
var salesChartData = {
datasets: [
{
data : {}
}
]
};
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
salesChartData.datasets[0].data = data;
});
Just set the data after receiving it
if you need to show the ajax result in a variable salesChartData, you can try this
salesChartData.datasets[0].data[0] = "new data"
salesChartData is a JSON object with key datasets contains an array of JSON objects.
So if salesChartData is declared globally, then you can replace in the success of the ajax
Here below, it done using web storage. This is used to access from different file.
// File 1
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
localStorage.setItem("salesChart", JSON.stringify(salesChartData));
//-----------------------------------------------------------------------
// File 2
var salesChartData = JSON.parse(localStorage.getItem("salesChart"));
// ajax call
$.getJSON('chartState', {
stateCode: $(this).val(),
ajax: 'true'
},
function (data) {
alert("state data" + data);
salesChartData.datasets[0].data[0] = data // "new data"
});
Hope this will work.
Thank You
I have done with my self
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
var chr=data;
var a=chr[0];var b=chr[1];var c=chr[2];var d=chr[3];
var e=chr[4];var f=chr[5];var g=chr[6];
After that I have sended one by one data
var salesChartData = {
datasets: [
{
data : [g,f,e,d,c,b,a]
}
]
};
As you mention that both parts of the script are in different tags you can solve the problem with a global, this is not recommended. The better solution would be to refactor the structure and not have multiple script tags. But if you have no control over this then you should do something like this:
<script>
// No var used to make it global
chart_state_data = false;
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
// the data is set to this variable on callback
chart_state_data = data
});
</script>
And:
<script>
// chart_state_data contains data retrieved from ajax call or false
var salesChartData = {
datasets: [{
data: chart_state_data
}]
};
</script>

Use variable as data in apexcharts

I'm trying to display a chart in apexcharts, and use a variable as the data. When I do this, nothing is displayed. See the following:
var message = '[1,4]'
var options = {
chart: {
type: 'line',
sparkline: {
enabled: true,
}
},
series: [{
data: message,
}],
}
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
Using the variable message as data doesn't work. When I switch the line:
data: message,
to
data: [1,4]
it displays correctly. However, I must use a variable. How do I do this?
You declared message variable as STRING, It is expecting an ARRAY
Please change
var message = '[1,4]'
to
var message = [1,4];

Parsing JSON data into an array for a C3.js chart

I'm sending a json variable from django to C3.js in this format:
{
datetime.date(2015, 5, 1): 22792461.479999978,
datetime.date(2015, 6, 1): 24807797.38999998,
datetime.date(2015, 7, 1): 25261456.609999962
}
I need to extract the values and compile them into an array ready for use by c3.js. Here's my script:
<script>
{% include "croydon_dashboards/dashboard_includes/gb_locale.html" %}
var row_value = {{ row_value }};
var sum_list = [];
for(var i in row_value)
sum_list.push(row_value[i])
sum_list = JSON.stringify(sum_list);
var chart = c3.generate({
data: {
columns: [
sum_list
],
type: 'bar'
},
bar: {
width: {
ratio: 0.5
}
}
});
</script>
Hard coding values into the chart works, so I know the c3.js is right, but there's something wrong with the way I'm building the array.
I know that there's an answer here: JSON Data doesn't show on c3.js bar chart
but I'm new to javascript and can't work out how to parse the json that I'm working with.
You do not need to JSON.stringify() your data to use it with c3.
But you may have to JSON.parse() it to make it look like this:
var row_value = {
"2015-05-01": 22792461.479999978,
"2015-06-01": 24807797.38999998,
"2015-07-01": 25261456.609999962
};
And don't forget to add text label at the beginning of data array:
// This first value of array if the name of your data
var sum_list = ['something'];
The rest of your code works.
for(var i in row_value)
sum_list.push(row_value[i])
var chart = c3.generate({
data: {
columns: [
sum_list
],
type: 'bar'
},
bar: {
width: {
ratio: 0.5
}
}
});
See this fiddle.

Converting Poloniex API Callback JSON into format suitable for Highcharts.Stockchart

I am trying to get JSON from Poloniex's public API method (specifically the returnChartData method) to display chart history of cryptocurrencies against one another into a Highchart Stockchart graph (looking like the demo one here.).
This is part of my JavaScript code to use the Poloniex returnChartData callback, get the JSON from it and implement it into the 'data' segment of the chart. So far it is not working and I can't for the life of me figure out what I need to change.
var poloniexUrl = "https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400";
$.getJSON(poloniexUrl, function(data){
results = data;
});
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'cryptoChart',
backgroundColor: 'white'
},
title: {
text: currentTitle
},
series: [{
data: results,
turboThreshold: 1000
}],
xAxis: {
original: false
},
rangeSelector: {
selected: 1
},
plotOptions: {
line: {
gapSize: 2
}
}
});
Would love any help!
Refer to this live demo: http://jsfiddle.net/kkulig/0f4odg5q/
If you use turboThreshold the points' options need to be given as an integer or an array (Explanation: https://api.highcharts.com/highstock/plotOptions.series.turboThreshold). In your case the format is JSON, so I disabled turboThreshold to prevent Higcharts error 12 (https://www.highcharts.com/errors/12):
turboThreshold: 0
$.getJSON is asynchronous - the best way to make sure that data variable is initialized is using it inside callback function (second argument of getJSON):
$.getJSON(poloniexUrl, function(data) {
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
(...)
The data that you fetch looks like candlestick series - I changed the type of the series:
type: 'candlestick'
Date will be properly understood by Highcharts if it's kept in the x property of JSON object (not date):
data: data.map((p) => {
p.x = p.date;
return p
}),

Categories

Resources