Converting a Json value from a string to an integer - javascript

I am trying to convert a JSON string into an integer so that I can use this data in a google chart. As of right now I can only get one set of data to be displayed in my chart.
Here is my JQUERY code:
$("#shotsandbigcc").click(function(){
//alert("Button works");
$("#shotsandbigcc_popup").toggle();
var integer = $("#shotsandbigcc").attr("name");
//alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {myData: integer},// data to submit
dataType: 'json',
success: function(response){
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMultSeries);
function drawMultSeries() {
var len = response.length;
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable([
['Year', 'Shots on Target', 'Shots off Target'],
[year, ontarget, offtarget],
[year, ontarget, offtarget]
]);
var options = {
title: 'Shooting Accuracy',
chartArea: {width: '50%'},
hAxis: {
title: 'Amount of Shots',
minValue: 0
},
vAxis: {
title: 'Year'
}
};
var chart = new google.visualization.BarChart(document.getElementById('shotsandbigcc_chart'));
chart.draw(data, options);
}
}
});
});
The JSON data is in an array which has this format [{"Year":"2019/2020","Shots_on_Target":"302","Shots_off_Target":"578","Accuracy":"0.34"},{"Year":"2020/2021","Shots_on_Target":"74","Shots_off_Target":"93","Accuracy":"0.44"}]
If someone could tell me how I can display both 2019/2020 and 2020/2021 data to be displayed. I would be most grateful as right now only the 2020/2021 data is being displayed. Thank you.

For integet value part:
var ontarget = parseInt(response[i].Shots_on_Target);
For your data part:
var vizData = [];
vizData.push(['Year', 'Shots on Target', 'Shots off Target']);
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
vizData.push([year, ontarget, offtarget]);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable(vizData);
explaination: since in the loop the values are getting updated in every iteration so, the 'year', 'ontarget' and 'offtarget' will have the latest values only. So on every iteration you have to store values so that they do not get overwritten. For that now this code is pushing in array in every iteration preserving the previous values. Which now you can use in the google.visualization function.
Happy Coding!

Related

CanvasJS not properly rendering chart

I am using the following code to render an OHLC chart in CanvasJS:
<script>
var candleData = [];
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: 'Demo Stacker Candlestick Chart (Realtime)'
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: 'Price',
prefix: '$'
},
axisX: {
interval: 1,
},
data: [{
type: 'ohlc',
dataPoints: candleData
}
]
});
function mapDataToPointObject(data) {
var dataPoints = [];
for(var i = 0; i < data.length; i++) {
var obj = data[i];
var newObj = {
x: new Date(obj.time),
y: [
obj.open,
obj.high,
obj.low,
obj.close
]
}
dataPoints.push(newObj);
}
return dataPoints;
}
function updateChart() {
$.ajax({
url: 'http://localhost:8080',
success: function(data) {
candleData = JSON.parse(data);
candleData = mapDataToPointObject(candleData);
chart.render();
}
});
}
$(function(){
setInterval(() => {
updateChart();
}, 500);
});
The data properly loads, parses into the correct format, and render() is called on the interval like it should. The problem is, while the chart axes and titles all render properly, no data shows up. The chart is empty.
What DOES work is setting the data directly to the chart using
chart.options.data[0].dataPoints = candleData;
Why does my above solution not work then? Is there a way I can update the chart's dataPoints without having to hardcode a direct accessor to the chart's dataPoints?
It's related to JavaScript pass by value and pass by reference.
After execution of the following line.
dataPoints: candleData
dataPoints will refer to the current value of candleData. ie. dataPoints = [];
Now if you redefine candleData to any other value.
candleData = JSON.parse(data);
candleData = mapDataToPointObject(candleData);
Then dataPoints won't be aware of this update and will still refer to the empty array (that you pointed earlier).
The following snippet will make it easy to understand
//pass by value
var a = "string1";
var b = a;
a = "string2";
alert("b is: " + b); //this will alert "string1"
//pass by reference
var c = { s: "string1" };
var d = c;
c.s = "string2";
alert("d.s is: " + d.s); //this will alert "string2"
For more, you can read about pass by value and pass by reference.
Javascript by reference vs. by value
Explaining Value vs. Reference in Javascript

Display dynamic data in Rickshaw chart retreived from API

I try to display data retrieved from web API via a ajex request using rickshaw. Data is retrieved correctly and added to an array. However the chart does not render any data. When I console the series data array it shows all data. Here is my code
var seriesData = [
[]
];
$.ajax({
url: "http://things.ubidots.com/api/v1.6/devices/Smart-
FAD/Temperature/values?page_size=50&format=json&&token=A1E-
BR1Y0dMLAULMNmMLbk0Y8qADGOdS5h",
type: "GET"
}).done(function(data) {
var result = data.results;
for (var i = 0; i < result.length; i++) {
var value = result[i].value;
var time = result[i].timestamp;
seriesData[0][i].push({
"x": time,
"y": value
});
};
}).fail(function() {
console.log("REQUEST FAILED");
});
var graph = new Rickshaw.Graph({
element: document.querySelector("#chart"),
width: 540,
height: 240,
series: [{
data: seriesData[0],
color: 'steelblue',
name: 'Server1'
}]
});
var x_axis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
var y_axis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
element: document.getElementById('y_axis'),
});
graph.render();
Can some help me to solve this?
Rickshaw doesn't watch for changes in the dataset automatically so you need to call graph.update() at the end of you ajax.done function.
.done(function(data) {
var result = data.results;
for (var i = 0; i < result.length; i++) {
var value = result[i].value;
var time = result[i].timestamp;
seriesData[0].push({
"x": time,
"y": value
});
};
graph.update()

Re-compile JSON data to make less rows

If I have a JSON result that has many rows, sometimes up to 100
Label:Part1 Value:1000
Label:Part2 Value:700
Label:Part3 Value:600
Label:Part4 Value:500
... and so on
I would like to change the data so that it lists the top 5 results as normal, but instead of listing the rest, it sums the value and changes the label to 'others'.
Example
Label:Part1 Value:1000
Label:Part2 Value:700
Label:Part3 Value:600
Label:Part4 Value:500
Label:Part5 Value:500
Label:other Value:25650
Is this possible to do in javascript, before I pass to a chart.js pie? Or is there a better method to achieve this?
Current code for pie
function chart1(branch, apitime){
$.ajax({
url: jsonpath' + apitime + branch,
dataType: 'jsonp',
success: function (response) {
console.log (response);
var datachart = response;
var ctx2 = document.getElementById("chart-area2").getContext("2d");
var myChart = new Chart(ctx2).Pie(datachart);
}
});
}
Data is sorted and I could change the SQL on the server to do this also, I just don't know what the correct method is to do that.
JSON example here http://pastebin.com/p3Y9mSX3
You can modify your data just before creating the chart.
var top6 = datachart.slice(0,5)
top6[5] = {
label: 'other',
value: datachart.slice(5).reduce(function(sum, data) {
return sum + data.value
}, 0)
}
var ctx2 = document.getElementById("chart-area2").getContext("2d");
var myChart = new Chart(ctx2).Pie(top6);
This can be made more general to get the top N entries
var getTopN = function(dataArray, n)
var tops = dataArray.slice(0, n)
tops[n] = {
label: 'other',
value: dataArray.slice(n).reduce(function(sum, data) {
return sum + data.value
}, 0)
}
return tops
}
var top5 = getTopN(datachart, 5)
var top10 = getTopN(datachart, 10)

HighStocks change AJAX parameters

My highstocks chart fetches JSON data from Yahoo and data from is structured like so "www.blahAAPLblah.com".
I want to change the value of AAPL in the URL to other company ticker symbols so that I can fetch the data and display it on my chart. If I change the string manually to GOOG then it will work fine. Also if I put var ticker = 'GOOG' and change the URL to "www.blah" + ticker + "blah.com" then this also works fine.
If I have a user input box and have var ticker = document.getElementById('userInput').value; then everything stops working.
Do you have any suggestions at all?
Here is my code so far: http://jsfiddle.net/SgvQu/
UPDATE I have attempted to use JSONP to perform the request but the chart is still not loading.
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
Thanks to Sebastian Bochan for pointing me in the right direction with JSONP. I now have the chart functioning correctly :)

Add another series to existing plot with flot

I need to know how I can easily add another series to an existing plot using Flot.
Here is how I currently plot a single series:
function sendQuery() {
var host_name = $('#hostNameInput').val();
var objectName = $('#objectNameSelect option:selected').text();
var instanceName = $('#instanceNameSelect option:selected').text();
var counterName = $('#counterNameSelect option:selected').text();
$.ajax({
beforeSend: function () {
$('#loading').show();
},
type: "GET",
url: "http://okcmondev102/cgi-bin/itor_PerfQuery.pl?machine=" + host_name + "&objectName=" + objectName + "&instanceName=" + instanceName + "&counterName=" + counterName,
dataType: "XML",
success: function (xml) {
var results = new Array();
var counter = 0;
var $xml = $.xmlDOM(xml);
$xml.find('DATA').each(function () {
results[counter] = new Array(2);
results[counter][0] = $(this).find('TIMESTAMP').text();
results[counter][1] = $(this).find('VALUE').text();
counter++;
});
plot = $.plot($("#resultsArea"), [{
data: results,
label: host_name
}], {
series: {
lines: {
show: true
}
},
xaxis: {
mode: "time",
timeformat: "%m/%d/%y %h:%S%P"
},
colors: ["#000099"],
crosshair: {
mode: "x"
},
grid: {
hoverable: true,
clickable: true
}
});
You can just add another results set:
// build two data sets
var dataset1 = new Array();
var dataset2 = new Array();
var $xml = $.xmlDOM(xml);
$xml.find('DATA').each(function(){
// use the time stamp for the x axis of both data sets
dataset1[counter][0] = $(this).find('TIMESTAMP').text();
dataset2[counter][0] = $(this).find('TIMESTAMP').text();
// use the different data values for the y axis
dataset1[counter][1] = $(this).find('VALUE1').text();
dataset2[counter][2] = $(this).find('VALUE2').text();
counter++;
});
// build the result array and push the two data sets in it
var results = new Array();
results.push({label: "label1", data: dataset1});
results.push({label: "label2", data: dataset2});
// display the results as before
plot = $.plot($("#resultsArea"), results, {
// your display options
});
At a high-level, the result of your call into itor_PerfQuery.pl will need to be extended to include the additional series data. You'll then want to make your "results" variable a multi-dimensional array to support the additional data and you'll need to update the current xml "find" loop which populates results accordingly. The remainder of the code should stay the same as flot should be able to plot the extended dataset. I think a review of the flot example will help you out. Best of luck.

Categories