How to convert String Format data [duplicate] - javascript

This question already has answers here:
Convert string with commas to array
(18 answers)
Closed 4 years ago.
I have a Json format like:
var d = "1,3,2,4"
How do I convert it into
var d = [3,5,3,6]
I tried this:
success: function (Response) {
debugger;
var du = (Response.d);
var final_string = '[' + du + ']'
// final_string = [1, 3, 2, 4];
console.log(final_string);
But this is not working, I want to final_string value as final_string = [1, 3, 2, 4];
actually i am trying to making a graph by this data
JvaScript
<script>
$(document).ready(function(){
debugger;
$.ajax({
type: "Post",
url: "Default.aspx/getdata",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
debugger;
var d = Response.d.toString();
var final_string = '[' + d + ']'
console.log(final_string);
//final_string = [1,3,2,4];
var options = {
chart: {
height: 250,
width:500,
type: 'line',
},
series: [{
name: ' ',
type: 'column',
data: final_string
}, {
name: '',
type: 'line',
data: final_string
}],
stroke: {
width: [0, 4]
},
title: {
text: 'Total Count'
},
labels: ['Birthady', 'Anniversary', 'Special', 'Total'],
xaxis: {
type: 'text'
},
yaxis: [{
title: {
text: 'Count Blog',
},
}, {
opposite: true,
title: {
text: ''
}
}]
}
debugger;
var chart = new ApexCharts(
document.querySelector("#chart"),
options
);
chart.render();
},
error: function (result) {
}
});
});
</script>
here the series data format is [1,3,2,4] and when i am passing data = [1,3,2,4] in series data graph is display in correct format and when i am passing final_string in series data graph is not display in correct format what is the main issue in this format final_string can any one help me
?

Why not use split(",") function. Since you're using the array on a chart you can use map(Number) to convert each item of the array to a Number type instead of a String.
var d = "1,3,2,4"
var res = d.split(",").map(Number);
console.log(res)
I based my response on the example in: ApexCharts
You need an array of Numbers like:
[2.3, 3.1, 4.0, 10.1, 4.0, 3.6, 3.2, 2.3, 1.4, 0.8, 0.5, 0.2]

success: function (Response) {
debugger;
var d = Response.toString();
var final_string = '[' + d + ']'
console.log(final_string);
}

Related

Bubble chart change X label values from a value in JSON response dynamically

I have a bubble chart using Chart.JS and getting my values dynamically from the database. The plotting of the data works absolutely fine, however I am trying to make a few formatting tweaks to the chart.
I want to change the X values to show the category (it is in my JSON output) on the horizontal axis rather than the i value. The JSON output contains category which is a string but I cant seem to do x: bubbleDatas[i].category?
The output currently shows on my x axis: 0,1,2,3,4,5 but i want it so show the value category from my JSON response which is in bubbleDatas?
data e.g.:
{
x: 0,
y: 60,
r: 10
}, {
x: 1,
y: 20,
r: 10
},
{
x: 2,
y: 40,
r: 10
}...
In my JSON response ajax request my X values i want it to be text:
e.g. 01_First, 02_Second
$(function () {
var bubbleData = [];
var xAxisLabels;
$.ajax({
type: "POST",
async: false,
url: "ExecView.aspx/ReturnData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var bubbleDatas = data.d;
bubbleData = new Array(bubbleDatas.length);
console.log(bubbleDatas);
for (i = 0; i < bubbleDatas.length; i++) {
if (bubbleDatas[i].score >= 60) {
rgbcolour = "#008000";
}
else if (bubbleDatas[i].score >= 50 && bubbleDatas[i].score < 60) {
rgbcolour = "#FFA500";
}
else {
rgbcolour = "#FF6347";
}
bubbleData[i] = { **x: i,** y: bubbleDatas[i].score, r: bubbleDatas[i].radius, backgroundcolor: rgbcolour };
console.log(bubbleData[i]);
}
}
});
var popData = {
datasets: [{
label: "Test",
data: bubbleData
}]
};
var bubbleOptions = {
responsive: true,
legend: {
display: false
},
tooltips: {
callbacks: {
label: function (t, d) {
return d.datasets[t.datasetIndex].label +
': (Category:' + t.xLabel + ', Score:' + t.yLabel + ')';
}
}
},
scales: {
yAxes: [{
ticks: {
// Include a % sign in the ticks
callback: function (value, index, values) {
return value + '%';
}
}
}]
}
};
var ctx5 = document.getElementById("bubble_chart").getContext("2d");
new Chart(ctx5, { type: 'bubble', data: popData, options: bubbleOptions });
});
Changing category to more meaning might be your specific requirement, check this fiddle if it helps bubble chartJS fiddle and check this labelling in chartJS
P.S. check out your condition for x-axis in the callback and print accordingly

Google chart: "Data column(s) for axis #0 cannot be of type string" eror

I'm trying to display a line chart of currency rates via google charts.
Basically i have 2 type of values:
Date (format iso8601)
Rate (decimal number)
when i'm trying to render the chart i get an error: "Data column(s) for axis #0 cannot be of type string"
Here is my code:
PHP array making:
$xml=simplexml_load_file('https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/ils.xml') or die("Error: Cannot create object");
$arrayForChart = array();
$arrayForChart["Date"] = "Rate";
foreach ($xml->DataSet->Series->Obs as $key => $value) {
$dateIso8601Format=$value['TIME_PERIOD'];
$rateForDate=(string)$value['OBS_VALUE'][0];
$arrayForChart["$dateIso8601Format"] = $rateForDate;
}
$arrayForChart = json_encode($arrayForChart);
Javascript
var arrayForChart;
$.ajax({
type: "POST",
url: ajaxUrl,
//data: {configuration: Config },
success: function (data) {
arrayForChart = data;
arrayForChart = $.map(arrayForChart, function (el) {
return el;
});//converting js object to js array
},
cache: false
});
google.charts.load("current", {packages: ["corechart", "line"]});
google.charts.setOnLoadCallback(drawLineColors);
function drawLineColors() {
var data = google.visualization.arrayToDataTable([arrayForChart]);
var options = {
hAxis: {
title: "Rate",
id: "Rate",
label: "Rate",
type: "number"
},
vAxis: {
title: "Date",
id: "Date",
label: "Date",
type: "string"
},
colors: ["#a52714", "#097138"]
};
var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
chart.draw(data, options);
}
Sample of data:
["Rate","4.7278","4.7301","4.6814"]
Anybody might know what is the problem?
Many thanks!

Data in highchart JSON format is correct

I have code like this
public static string summarydata(string RegNo)
{
try
{
TrackDataEntities1 sd = new TrackDataEntities1();
var mdata = new TrackDataEntities1().spsumdata(RegNo)
.Select(s => new { month = s.Month }).ToArray();
var sdata = new TrackDataEntities1().spsumdata(RegNo)
.Select(s => new { s.VName, s.total }).ToArray();
return Newtonsoft.Json.JsonConvert.SerializeObject(mdata) + "*" + Newtonsoft.Json.JsonConvert.SerializeObject(sdata);
}
catch (Exception)
{
throw new Exception();
}
}
now this return me data like this
"[{\"month\":\"July\"},{\"month\":\"June\"},{\"month\":\"June\"},
{\"month\":\"August\"},{\"month\":\"July\"},{\"month\":\"June\"},
{\"month\":\"May\"},{\"month\":\"June\"}]*[{\"VName\":\"DDSB\",\"total\":1},
{\"VName\":\"DPSB\",\"total\":1},{\"VName\":\"DSB\",\"total\":1},
{\"VName\":\"MV\",\"total\":5},{\"VName\":\"MV\",\"total\":11},
{\"VName\":\"MV\",\"total\":7},{\"VName\":\"MV\",\"total\":1},
{\"VName\":\"PSB\",\"total\":1}]"
jquery
UPDATED JQUERY
$(function () {
$('#tabledata').on('click', 'tr', function () {
var row = $(this);
var regno = row.find('td')[0].firstChild.data;
var obj = {};
obj.RegNo = regno;
Getsumdata(obj);
return false;
});
});
function Getsumdata(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/summarydata",
data: JSON.stringify(obj),
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(JSON.stringify(result.d));
var data1 = result.d.split('*')[0];
console.log(typeof (data1)); //Still a String...
var data11 = JSON.parse(data1);
console.log(data11); //
$('#sum').highcharts({
title: {
text: 'Combination chart'
},
xAxis: {
categories: data11,
title: {
text: null
}
},
labels: {
items: [{
html: 'Total fruit consumption',
style: {
left: '50px',
top: '18px',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
}
}]
},
// series:data2
series: [{
type: 'column',
name: 'Jane',
data: [3, 2, 1, 3, 4]
}, {
type: 'column',
name: 'John',
data: [2, 3, 5, 7, 6]
}, {
type: 'column',
name: 'Joe',
data: [4, 3, 3, 9, 0]
},
]
});
}
});
}
</script>
but chart look like this
Now the question is JSON look correct i think so why data is not populated in chart .. i use BAR highchart
any solution please?
data2 is still a string, you have to parse it.
Take a look at the Docs on how to add chart data, you have to transform your current data.
var a = "[{\"month\":\"July\"},{\"month\":\"June\"},{\"month\":\"June\"}, {\"month\":\"August\"},{\"month\":\"July\"},{\"month\":\"June\"}, {\"month\":\"May\"},{\"month\":\"June\"}]*[{\"VName\":\"DDSB\",\"total\":1}, {\"VName\":\"DPSB\",\"total\":1},{\"VName\":\"DSB\",\"total\":1}, {\"VName\":\"MV\",\"total\":5},{\"VName\":\"MV\",\"total\":11}, {\"VName\":\"MV\",\"total\":7},{\"VName\":\"MV\",\"total\":1}, {\"VName\":\"PSB\",\"total\":1}]";
var d = a.split('*')[1];
console.log(typeof(d)); //Still a String...
var e = JSON.parse(d);
console.log(e); //Yay an object.
It seems that you are not passing correct data to categories and series's.
Please transform your data in such a way that,
data1 represent categories, should look like this
["May","June","July","August"]
while your data2 represent the series data which you want to plot for a given month, should look like below.
[1,10,12,5]

Unable to plot data json data on highcharts

I am trying to load json data to high-charts. I am receiving json data from DB using $.getJSON function. Here is my sample json that i am receiving from DB,
My sample json
[
{
"target":"collectd.matrix.oracle.avg_resp_time","datapoints":[[8.0, 1365158480],[null, 1365158490],[null, 1365158500],[null, 1365158510],[null, 1365158520],[null,1365158530],[8.0, 1365158540],[null, 1365158550],[null, 1365158560],[null, 1365158570],[null, 1365158580],[null, 1365158590]]
}
]
$.getJSON("myURL", createOrderDurationChart);
On success response from $.getJSON i call function below,
I am using scala framework.
I am not getting what is wrong in code or json. I can plot this json by embedding code in simple javascript and run through html directly as sample.
Here is the sample code,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
jsondata= durationMap[0].datapoints;
alert(jsondata)
var datapoints=JSON.parse(jsondata);
// var jsonstr=parsejson[0].datapoints;
console.log('jsotn ' + datapoints);
// var mydata = JSON.parse(jsonstr);
// alert(mydata);
// datapoints = mydata[0].datapoints;
//alert("initial:" + json[0].time + ':' + json[0].value);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Update code after json fix,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
datapoints= durationMap[0].datapoints;
console.log('jsotn ' + datapoints);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Any suggestions most welcome.
Thanks

onClick takes two clicks to populate results, HighCharts

My issue revolves around having to click a button twice to populate the results desired. I am using HighCharts to draw a chart, but the updateTime3Period() function must be called twice before the chart is properly displayed. Below I have included all my code, except for the updateTime6Period() function, since it is the same as updateTime3Period() in most ways. They both have the same issue. I would like to have the button be clicked once, and then populate the desired chart. I apologize for the lengthy post. Thank you in advance! Note: This does work if updateTime3Period() is clicked twice.
HTML:
<div id="timelinePeriods">
<ul class="timeSelection">
<li><a href="#" onclick="updateTime6Period();" > Past 6 Periods</a></li>
<li> Past 3 Periods</li>
</ul>
</div>
JS/AJAX for updateTime3Period:
function updateTime3Period() {
timeFrameUpdate = 'Past 3 Periods';
displayParam();
$.ajax({
url: 'PHP/getValues.php',
type: 'post',
data: {
type: "A",
type2: B,
type3: C,
type4: D,
type5: E,
type6: F,
type7: "getChartCurr"
},
success: function(response2) {
obj2 = JSON.parse(response2);
}
});
$.ajax({
url: 'PHP/getValues.php',
type: 'post',
data: {
type: "A",
type2: B,
type3: C,
type4: D,
type5: E,
type6: F,
type7: "getChartPrev"
},
success: function(response3) {
obj3 = JSON.parse(response3);
}
});
updateCharts(obj2, obj3, measureUpdate);
}
Functions that are called above (same file):
function displayParam() {
document.getElementById("params").innerHTML = timeFrameUpdate;
}
function updateCharts(data1, data2, measureData) {
} else if (timeFrameUpdate == 'Past 6 Periods') {
updateSixMonthPeriodChart(data1, data2, measureData);
} else if (timeFrameUpdate == 'Past 3 Periods') {
updateThreeMonthPeriodChart(data1, data2, measureData);
}
HighCharts Graph:
function updateThreeMonthPeriodChart(data1, data2, measureData) {
var measureValue = data1["graph"];
var measureValuePrev = data2["graphPrev"];
var changeValue = new Array();
for (i = 0; i < 3; i++) {
measureValue[i] = parseInt(measureValue[i]);
changeValue[i] = (parseInt(measureValue[i]) - parseInt(measureValuePrev[i])) / parseInt(measureValuePrev[i])
}
var chart1; // globally available
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'myChart',
},
title: {
text: 'Sales and Percent Change vs. Last Year - Past 3 Periods'
},
xAxis: {
categories: [1, 2, 3],
title: {
text: 'Period'
},
},
yAxis: [{
labels: { //Right y-axis
formatter: function() {
return Highcharts.numberFormat(this.value, 1, '.', ',') + '%';
}
},
title: {
text: '% Change'
},
opposite: true
},
{ //Left y-axis
labels: {
formatter: function() {
return '$' + Highcharts.numberFormat(this.value, 0, '', ',');
}
},
title: {
text: 'Sales ($)'
}
},
],
series: [{
name: 'Sales',
data: [measureValue[0], measureValue[1], measureValue[2]],
color: '#363534',
//Charcoal
yAxis: 1,
type: 'column'
},
{
name: '% Change',
data: [changeValue[0], changeValue[1], changeValue[2]],
color: '#E17000',
//Pumpkin
//yAxis: 2,
type: 'spline'
}]
});
});
}
It might be cause of your ajax request, it didn't complete at first click.in the next click it get the result from the catch and runs faster.
try this :
function updateTime3Period() {
timeFrameUpdate = 'Past 3 Periods';
displayParam();
$.ajax({
url : 'PHP/getValues.php',
type : 'post',
data : {
type : "A",
type2 : B,
type3 : C,
type4 : D,
type5 : E,
type6 : F,
type7 : "getChartCurr"
},
success : function (response2) {
obj2 = JSON.parse(response2);
$.ajax({
url : 'PHP/getValues.php',
type : 'post',
data : {
type : "A",
type2 : B,
type3 : C,
type4 : D,
type5 : E,
type6 : F,
type7 : "getChartPrev"
},
success : function (response3) {
obj3 = JSON.parse(response3);
updateCharts(obj2,obj3,measureUpdate);
}
});
}
});
}

Categories

Resources