Csv data could not be loaded in c3 chart - c3.js

This is the javascript file which is added in html file.I Tried using all possible paths but still this is not working. Thanks in advance
<div id="chart"></div>
<script>
var chart = c3.generate({
data: {
url: 'data.csv',
type: 'bar'
},
bar: {
width: {
ratio: 0.5
}
},
axis: {rotated : true}
});
</script>

Related

Google Chart - Refresh Data from Google Sheet without Page Refresh

New to coding here and I have a WordPress page that displays a Google Chart with the source data coming from a Google Sheet where I'm trying to have the Google Chart redraw/refresh the data automatically without manually refreshing the entire web page.
Below is my current code which works to only refresh the data in the chart when a user manually refreshes the entire website.
I have read about AJAX and it seems this is the key but I haven't been able to tweek the Google Developer example code to solve my issue.
I hit a road block at ...
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
where I do not know how to get my public google sheet URL to work in place of the "getData.php" part of the code snippet above. I do not know anything about php but saw examples where people reformatted their google sheet URL is lieu of using the php part to something like:
https://spreadsheets.google.com/feeds/list/1gwLrZtvDBSQPdXl_L1cOl_y2318yiVXKwgN2-czdgW0/1/public/basic?alt=json
but that still doesn't work for me. Feels like I'm going down a rabbit hole just trying to get the data using this approach when I already have a way to get the same data (tho without it automatically refreshing without manually reloading the entire website). Any help will be greatly appreciated!
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_1" style="width: 700px; height: 400px;"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization1);
function drawVisualization1() {
var query = new google.visualization.Query( 'https://docs.google.com/spreadsheets/d/1gwLrZtvDBSQPdXl_L1cOl_y2318yiVXKwgN2-czdgW0/gviz/tq?gid=0&headers=1&tq?&range=A1:E13');
query.send(handleQueryResponse1);
}
function handleQueryResponse1(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
title : 'Sales ($) and Margin (%)',
titleTextStyle: {
fontSize: 16,
},
legend: {position: 'top', maxLines: 2},
pointSize: 7,
series: {
0: {type: 'bars', targetAxisIndex: 0},
1: {type: 'bars', targetAxisIndex: 0},
2: {type: 'bars', targetAxisIndex: 0},
3: {type: 'line', targetAxisIndex: 1},
},
vAxes: {
0: {title: 'Sales ($ in millions)'},
1: {title: 'Margin (%)', gridlines: {color: 'transparent'}, format:"#%"}},
hAxis: {title: 'Fiscal Quarter', slantedText: 'True'},
isStacked: 'True',
};
var data = response.getDataTable();
var chart = new google.visualization.ComboChart(document.getElementById('chart_1'));
chart.draw(data, options);
}
</script>
You can use setRefreshInterval(seconds) to call query.send() every few seconds.
query.setRefreshInterval(120);
query.send(handleQueryResponse1);
you don't need ajax, because you're using google.visualization.Query to get the data.
just need to structure you're code in such a way,
that you can refresh the data and chart,
without rebuilding everything.
see following working snippet,
the chart and options are created once.
the data is retrieved initially, and when the button is clicked.
after receiving the data, the chart is drawn.
I added the 'ready' event to the chart, just to prove the data was refreshed and the chart re-drawn.
but since the data doesn't actually change, nothing appears to happen.
google.charts.load('current', {
packages: ['corechart']
}).then(drawVisualization1);
function drawVisualization1() {
var chart = new google.visualization.ComboChart(document.getElementById('chart_1'));
google.visualization.events.addListener(chart, 'ready', function () {
console.log('drawn');
});
var options = {
title : 'Sales ($) and Margin (%)',
titleTextStyle: {
fontSize: 16,
},
legend: {position: 'top', maxLines: 2},
pointSize: 7,
series: {
0: {type: 'bars', targetAxisIndex: 0},
1: {type: 'bars', targetAxisIndex: 0},
2: {type: 'bars', targetAxisIndex: 0},
3: {type: 'line', targetAxisIndex: 1},
},
vAxes: {
0: {title: 'Sales ($ in millions)'},
1: {title: 'Margin (%)', gridlines: {color: 'transparent'}, format:"#%"}
},
hAxis: {title: 'Fiscal Quarter', slantedText: 'True'},
isStacked: 'True',
};
getData();
document.getElementById('refresh').addEventListener('click', getData);
function getData() {
var query = new google.visualization.Query( 'https://docs.google.com/spreadsheets/d/1gwLrZtvDBSQPdXl_L1cOl_y2318yiVXKwgN2-czdgW0/gviz/tq?gid=0&headers=1&tq?&range=A1:E13');
query.send(handleQueryResponse1);
}
function handleQueryResponse1(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
chart.draw(data, options);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<input id="refresh" type="button" value="Refresh" />
<div id="chart_1"></div>

Can't get c3 chart to render using Vue.js

Simple example won't render. Here is my code:
main.js
var Vue = require('vue');
var c3 = require('c3');
new Vue({
template: '<div id="puppa"></div>',
mounted: function () {
c3.generate({
bindto: '#puppa',
data: {
type: 'area',
x: 'x',
xFormat: '%H:%M',
columns:[
['x',"12:38","12:38","12:38","12:38","12:39","12:39","12:39","12:39","12:40","12:40","12:40","12:41","12:41","12:41","12:41","12:42","12:42","12:42","12:42","12:43","12:43","12:43","12:43","12:44","12:44"],
['write', 14709198848,14709313536,14709522432,14709633024,14710034432,14710157312,14710341632,14710583296,14710788096,14710931456,14711058432,14711291904,14711508992,14711668736,14711771136,14712008704,14712107008,14712381440,14712586240,14712795136,14712963072,14713077760,14713331712,14713565184,14713729024],
['read', 3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080,3778094080]
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: function (x) {
if (x.getDate() === 1) {
return x.toLocaleDateString();
}
}
}
}
}
});
}
});
In your HTML.
<div id="app"></div>
Or whatever other id you want to use. You need to give your Vue an element to render it's template to. In your Vue
new Vue({
el: "#app",
mounted: function() {
c3.generate({
bindto: this.$el,
...
})
}
})
Here is an example.
Also ran across the need to downgrade the d3 version with c3.

CanvasJS Column chart with external json data not loading

Im trying to load this column chart with external data in Json format from a file
I have a jsfiddle with what i have so far.
Thanks for any help.
http://jsfiddle.net/t9n4d8z4/1/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({
label: result[i].label,
y: parseInt(result[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: result
}]
});
chart.render();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
json format was not handled properly.
Here is the working fiddle : http://jsfiddle.net/canvasjs/t9n4d8z4/3/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.dataPoints.length - 1; i++) {
dataPoints.push({
label: result.dataPoints[i].label,
y: parseInt(result.dataPoints[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: dataPoints
}]
});
chart.render();
});
});
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

Redrawing Google Pie Chart with AJAX

I am using the following pie chart code that is being fed data from a query:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Customers', 'Status'],
['Accepted', <?php echo $rowsaccepted ;?>],
['Declined', <?php echo $rowsdeclined;?>],
['Not Reviewed', <?php echo $rowsnreview;?>]
]);
var options = {
'width':200,
'height':200,
'backgroundColor':'#474747',
'legend': 'none',
'chartArea':{left:20,top:0,width:250,height:250},
colors: ['#ef8200', '#007fc2', '#41cf0f'],
fontSize:14,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
and the following AJAX call that updates my DB upon clicking a button; therefore updating the chart data, but I must refresh the page for the chart to refresh:
<script type="text/javascript">
$(function() {
$(".decline").click(function(){
var element = $(this);
var del_id = element.attr("id1");
var order_id = element.attr("data-order1");
$.ajax({
type: "POST",
url: "decline.php",
data: {id1:del_id,order_id1:order_id},
success: function(){cache: false}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
});
});
</script>
Is there any way I can add a call in my AJAX function that will refresh and redraw the pie chart without requiring the page to be refreshed?
Thanks!

data-bind not working in List View template within Grid detail template

I need help using a Kendo UI list view which lives within a grid row detail template.
here is something I have done so far.
<div id="grid">
</div>
<script type="text/x-kendo-template" id="gridDetailTemplate">
<div class='grid-edit'>
<div class='edit-list'></div>
</div>
</script>
<script type="text/x-kendo-template" id="editItemtemplate">
<div class='edit-Item'>
#if(Type=='string'){#
<ul><li><b>#:Name#</b></li><li><input class='inputString' value='#:DataVal()#'/></li></ul>
#}else if(Type=='number'){#
<ul><li><b>#:Name#</b></li><li><input class='inputNumber' data-role='numerictextbox' data-type='number' value='#:DataVal()#'/></li></ul>
#}else if(Type=='date'){#
<ul><li><b>#:Name#</b></li><li><input class='inputDate' data-role='datepicker' value='#:kendo.toString(DataVal(),'MM/dd/yyyy')#'/></li></ul>
#}else if(Type=='boolean'){Name #<input type='checkbox'/>
#}#
</div>
</script>
<script type="text/javascript">
$(document).ready(function () {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var selFields = new Object();
$.each(data, function (index, elem) {
selFields[elem.Name] = new Object();
selFields[elem.Name]["type"] = elem.Type;
});
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: { url: "http://localhost:4916/Deal",
dataType: "json"
}
},
schema: {
data: "Data", total: "Total",
model: {
fields: selFields
}
}
},
height: 430,
filterable: true,
sortable: true,
pageable: false,
detailTemplate: kendo.template($("#gridDetailTemplate").html()),
detailInit: detailInit,
columns: [{
field: "SecurityName",
title: "Security Name",
width: 250
},
{
field: "DateOfAcquisition",
title: "Date Of Acquisition",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "Acres",
title: "Acres",
width: 120
}
]
});
});
});
function detailInit(e) {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var detailRow = e.detailRow;
detailRow.find(".edit-list").kendoListView({
dataSource: {
data: data,
schema: {
model: {
DataVal: function () {
switch (this.get("Type")) {
case "number"
}
if (e.data[this.get("Name")])
return e.data[this.get("Name")];
else
return '';
}
}
}
},
template: kendo.template($("#editItemtemplate").html())
});
});
}
</script>
My code gets dynamic field list and binds it to the data source for grid.
Then, in the detailInit event, I find the div within row detail and convert it into kendo UI list, for which the template have been created.
Now, when I use data-bind="value: DataVal()" ,it doesn't pick up the values of List data source. It works the way I have done i.e. value="#: DataVal() #". But, data-role does not convert the fields to specified types which are datepicker and numericinput in my case.
I believe that data-role not being used is caused due to same issue as data-bind not being read.
Can anyone help me out with this? Also, feel free to suggest any alternate ways and general code improvements. I am an ASP.NET developer and usually don't work on pure html and javascript.
PS: I would be happy to provide the context on what I am trying to achieve here if anyone is interested.
Thanks in advance.
If you can rig up a jsFiddle or jsBin example that would help debug the issue.
However, try removing the parenthesis:
data-bind="value: DataVal"
Kendo should detect that DataVal is a function and call it on its own.
I experienced a similar situation in a listview template. I created a JSFiddle to demonstrate:
http://jsfiddle.net/zacharydl/7L3SL/
Oddly, the solution is to wrap the contents of the template in a div. It looks like your template already has this, so YMMV.
<div id="example">
<div data-role="listview" data-template="template" data-bind="source: array"></div>
</div>
<script type="text/x-kendo-template" id="template">
<!--<div>-->
<div>method 1: #:field#</div>
<div>method 2: <span data-bind="text: field"></span></div>
<input data-role="datepicker" />
<!--</div>-->
</script>
var model = kendo.observable({
array: [
{ field: 'A'},
{ field: 'B'}
]
});
kendo.bind($('#example'), model);

Resources