Highcharts error csv.replace is not a function - javascript

I'm working on parsing some data from a CSV file, but i get this error :
Uncaught TypeError: csv.replace is not a function
I don't know why, can somebody help me ?
This is my loadCSV.js:
jQuery(document).ready(function($) {
var parse;
var csv = Papa.parse("http://1001dev.com/Chahine/wp-content/themes/consulting-child/fonds/DigitalStarsEurope/volatilityFR.csv", {
download: true,
complete: function(results) {
console.log(results.data);
$("#EuropeVolatilityBtn").click(function() {
$('#EuropeVolatility').highcharts({
data: {
csv: results
}
});
});
}
});
});
You can see the result here in :
http://1001dev.com/Chahine/fonds/
When you click on the button : Volatilité the message appear.
Thanks a lot,
Cheers,
Jordan

You've already parsed your CSV file into json using Papa.parse. Highcharts data is looking for a CSV string, not a json object.
Also, why are you fetching the CSV file outside the click handler? The CSV will be downloaded even if the user never clicks on that button.
See: https://www.highcharts.com/docs/working-with-data/data-module
$.get('data.csv', function(csv) {
$('#container').highcharts({
chart: {
type: 'column'
},
data: {
csv: csv
},
title: {
text: 'Fruit Consumption'
},
yAxis: {
title: {
text: 'Units'
}
}
});
});

In addition to what #Barbara said, you can use Highcharts data module and parse your data adequately inside complete function. Take a look at the example posted below.
API Reference:
http://api.highcharts.com/highcharts/data.complete
Example:
http://jsfiddle.net/ny0qh8o3/

Related

HighChart Line Graph not Showing

I am using data from a csv file to generate a line graph using Highchart. Here is my code:
/* Define Initial and basic Options */
var options = {
chart: {
type: 'line',
renderTo: 'graph_container'
},
title: {
text: 'FanniemaeAcquisition Cash Flow'
},
yAxis: {
title: {
text: 'Amount($)'
}
},
series: []
};
/* Parse CSV File */
$.get('{% static "data/FanniemaeAcquisitions.csv" %}', function(csv) {
var lines = csv.split('\n');
var series = {
name: '',
data: []
};
$.each(lines, function (lineNo, line) {
var items = line.split(',');
$.each(items, function (itemNo, item) {
if(itemNo == 1){
if (lineNo == 0){
series.name = item;
} else {
series.data.push(parseFloat(item));
}
}
});
});
options.series.push(series);
console.log(options.series);
});
// Create the chart
var chart = new Highcharts.Chart(options);
However this isn't working. I tried testing it by manually inputting data like so:
series: [{
name: 'Installation',
data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
},
and that works fine. So I took a look at the variables being passed to series. The one that works(manual input):
The one that doesn't work(From CSV):
Any ideas?
EDIT: Okay. something weird is going on here. Highchart isn't showing on the webpage but it showing when I download as PNG. The weirder part is that it shows on the webpage if I MANUALLY add in number values but when I extract the values form CSV the graph disappears... But when I download as PNG it shows the graph...Any ideas??
SECOND EDIT: Okay, so when I do: console.log(JSON.stringify(options.series[0].data));
nothing shows up. This would mean that the values parsed from the csv file appear after the graph is generated. So how do I fix this? lol
The problem was due to Javascript's Asynchronous Issues. I simply wrapped my function in a $.when and it worked!

setData is not a function + Angular2-Highcharts

I was following simple example to set data to Highcharts using this Angular2-Highcharts module
As shown in the following example, i have made small tweak to dynamically set data to Highcharts. Following is the code snippet :
constructor() {
this.options = {
chart: { type: 'spline' },
title: { text : 'dynamic data example'},
series: [{ data: [2,3,5,8,13] }]
};
setTimeout(() => {
this.chart.series[0].setData([21,31,51,81,13]);
}, 3000);
setTimeout(() => {
this.chart.series.push({data:[]});
this.chart.series[1].setData([100,200,300]);
}, 5000);
}
Plunker link for the same .
Error :
ERROR TypeError: _this.chart.series[1].setData is not a function
at eval (run.plnkr.co/QZBbWi3BVy3DeOzT/app/main.ts!transpiled:28)
My Observation :
What is evident with that error is there is no setData function in the series array in the 1st element. Alternate approach to resolve this is, initializing this.options with empty object with data property :
constructor() {
this.options = {
chart: { type: 'spline' },
title: { text : 'dynamic data example'},
series: [{ data: [2,3,5,8,13] },
{ data: [] },
]
};
}
This is very crude way as i need to do the same for 50 elements in this.options.series if i see them coming dynamically
Is there any efficient and better approach to resolve this error ?
PS : Am new to Highcharts, so please bear with me if am doing something completely wrong at basic level.
setData modifies a series which already exists - if you do not have the series you cannot modify it.
If you want to add a new series, you should use chart.addSeries() method like this:
setTimeout(() => {
this.chart.addSeries({
data: [21,31,51,81,13]
});
}, 5000);
example: http://plnkr.co/edit/61IgH8t3YKjtIOgzpUPB?p=preview

Automatically create header from JSON file, Bootstrap-table

I'm working with this bootstrap library and actually everything works fine. The question is, Can bootstrap-table generate header automatically in depend of JSON file? I've tried to find any information about that, but unlucky. Now my header is generated from script like from this example:
function initTable() {
$table.bootstrapTable({
height: getHeight(),
columns: [{
field: 'field1',
title: 'title1',
sortable: true
}, {
field: 'field2',
title: 'title2',
sortable: true
}, {
field: 'field3',
title: 'title3',
sortable: true
}, {
field: 'Actions',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
}
],
formatNoMatches: function () {
return "This table is empty...";
}
});
Does anyone how to generate header automatically?
Populating from a flat json file is definetly possible but harder than from a seperate (slimmer and preped) data request, because title and other attributes 'might' have to be guessed at.
Ill show basic approach, then tell you how to make it work if stuck with a flat file that you CAN or CANT affect the format of (important point, see notes at end).
Make a seperate ajax requests that populates var colArray = [], or passes direct inside done callback.
For example, in callback (.done(),.success(), ect) also calls to the function that contains the js init code for the table.
You might make it look something like this:
function initTable(cols) {
cols.push({
field: 'Actions',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
});
$("#table").bootstrapTable({
height: getHeight(),
columns: cols,
formatNoMatches: function () {
return "This table is empty...";
}
});
}
$(document).ready(function(){
$.ajax({
method: "POST",
url: "data/getColumns",
// data: { context: "getColumns" }
datatype: "json"
})
.done(function( data ) {
console.log( "getCols data: ", data );
// Prep column data, depending on what detail you sent back
$.each(data,function(ind,val){
data.sortable = true;
});
initTable(data);
});
});
Now, if you are in fact stuck with a flat file, point the ajax towards that then realise the question is whether you can edit the contents.
If yes, then add a columns array into it with whatever base data (title, fieldname, ect) that you need to help build your columns array. Then use responseHandler if needed to strip that columns array if it causes issues when loading into table.
http://bootstrap-table.wenzhixin.net.cn/documentation/#table-options
http://issues.wenzhixin.net.cn/bootstrap-table/ (click 'see source').
If no, you cant edit contents, and only have the fieldname, then look at using that in the .done() handler with whatever string operation (str_replace(), ect) that you need to make it look the way you want.

How do I pass a PHP variable from one file to another multiple times?

I have a highstock graph in a file called charts.php that reloads the graph data from a secondary file called data.php. Seeing as I have 5 series in my highstock graph I have to call the data.php file 5 times, each time using a different variable, but when I set the variable in my charts.php file it only uses the last set value of this variable. Is is possible to solve this, or is this just the way PHP works? Do I have to create 5 separate data.php files in order for this to work?
Here's basically what my code looks like (showing 2 series to keep it short):
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'chart'
},
title : { text : 'MyChart' },
series : [
{
name : 'Unit 0',
data : [],
tooltip: { valueDecimals: 1, valueSuffix: ' kW' },
},
{
name : 'Unit 1',
data : [],
tooltip: { valueDecimals: 1, valueSuffix: ' kW' },
}
]
});
<?php $_SESSION["unit"] = 0; ?>
$.getJSON( "data.php", function (data) {
chart.series[0].setData( data );
});
<?php $_SESSION["unit"] = 1; ?>
$.getJSON( "data.php", function (data) {
chart.series[1].setData( data );
});
So the problem is that both series[0] and series[1] use the last value of my variable, which in this case is $_SESSION["unit"] = 1. Is the a way to make this work? Any better alternatives?
Maybe if I could create data for all of the series in one file and somehow split that data and pass it to series[0] and series[1] separately, but I have no idea how to do that..
Any help is appreciated.
Maybe you could modify your data.php file, so instead of using $_SESSION["unit"] to determine which var to use, use $_GET["unit"] instead. Then, in your code above, it would be:
$.getJSON( "data.php?unit=0", function (data) {
chart.series[0].setData( data );
});
$.getJSON( "data.php?unit=1", function (data) {
chart.series[1].setData( data );
});
It depends on your needs, if the $unit values are always the same I would just call data.php once and update all the graphs at once using the JS response.
If $unit has a dynamic variable I would send it along with the $.getJSON function.
var data = {
unit: $_GET['unit']
};
$.getJSON( "data.php", data, function (response) {
updateGraph(graph, response);
});
For more on getJSON on the structure of the function, visit http://api.jquery.com/jquery.getjson/

Parsing Data From HTML Table

I am using the data.js plugin for highcharts. Using their basic demo I have created my own test version using our .NET generated table. The documentation on this is very sparse (essentially it is what is in data.src.js). I am getting errors that it is sending in data values as strings (HC error #14). I am not entirely sure how to modify the code to make it work with my simple table.
Here is my js code:
$(function () {
$('#container').highcharts({
data: {
table: document.getElementById('ctl00_Main_content_ucDashboard_ctl00_ctl11_ctl02_lstData_tblData')
},
chart: {
type: 'column'
}
});
});
Additional info:
It appears that the issue is that my table cells contain span tags encapsulating the values. I have no control over those tags and are there for presentation.
The <span> tags within the table are the problem. Try this:
$(function () {
$('#container').highcharts({
data: {
table: $('#ctl00_Main_content_ucDashboard_ctl00_ctl11_ctl02_lstData_tblData').clone(true).find('span').replaceWith(function() { return this.innerHTML; }).end()[0]
},
chart: {
type: 'column'
},
title: {
text: ''
}
});
});
(you could also simply remove the span tags from where ever they are coming from)
http://jsfiddle.net/5Gjyy/

Categories

Resources