javascript canvasjs Get data points dynamically from file.txt - canvasjs

Objective:
I want to get data from file.txt thats is saved local in /var/www/html/file.txt and use it for the doughnut chart on my webpage dynamically on a interval of 2 seconds
file.txt only has one entry and looks like:
34
the javascript i have tried:
$.get("file.txt", function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
dataPoints.push({y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "doughnut",
dataPoints : dataPoints,
}]
});
chart.render();
});
}
Entire html looks like
<!DOCTYPE html>
<html>
<head>
<title>Chart using txtfile Data</title>
<script type="text/javascript" src="http://canvasjs.com/assets/script /jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : [function()
{
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
xVal +=.25;
dataPoints.push({x : xVal, y: parseInt(allLines[i])});
}
}
}]
}]
});
chart.render();
},'text');
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>

I believe something like this may work for you. You may have to use Firefox as Chrome doesn't like cross origin requests
First, dataPoints was undefined, I moved the code into a function inside dataPoints. I changed your variable name from x to xVal. Added the 'text' word so the $get knows what format it's reading and also there was an extra bracket it seemed. Give this a try.
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var dps = [];
for(var i=0; i< allLines.length; i++) {
xVal +=.25;
dps.push({x : xVal, y: Number(allLines[i])});
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dps
}]
});
chart.render();
},'text');

Related

CanvasJS changing chart-type based on drop-down value

I want to change the chart-type based on the drop-down value. I had tried and followed the example but it still unable to work. I'm not sure which part that i had missed. I am using JavaScript Charts & Graphs from JSON Data Using AJAX. The code below:
<script src="../js/custom.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<script>
window.onload = function () {
var dataPoints = [];
$.getJSON( "<?php echo $url; ?>", function( json ) {
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
})
.done(function(){
alert("Completed");
})
.fail(function(e){
console.log('error:');
console.error(e);
})
.always(function(){
alert("always runs");
});
}
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
</script>
Drop-down list:
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>
Thank you in advance.
It just seems like variable scope issue, you are creating chart inside AJAX but trying to access it outside during changing the chart type, it would have thrown error in Browser Console. I would suggest you to do it outside AJAX and update just dataPoints inside AJAX.
Here is the updated / working code (Sample JSON with just 1 dataPoint is stored in: https://api.myjson.com/bins/18hgaa):
var dataPoints = [];
var chart;
$.getJSON("https://api.myjson.com/bins/18hgaa", function(json){
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
}).done(function(){
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
});
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>

Want to highlight/change color of certain words in Ace Editor?

I am setting text using the following:
var someString = 'Mark has solved the problem';
editor.getSession().setValue(someString);
In above case, Need only 'Mark' to appear in blue color.
Is there a way to load html tags in ace editor or manipulate styling of certain words?
You can create custom highlight rules to do this
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<meta charset="utf-8">
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.ace_customTokenName {color: darkred}
</style>
</head>
<body>
<div id="editor" style="height: 500px; width: 800px"></div>
<script src="https://ajaxorg.github.io/ace-builds/src/ace.js"></script>
<script>
define('ace/mode/custom', [], function(require, exports, module) {
var oop = require("ace/lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var CustomHighlightRules = require("ace/mode/custom_highlight_rules").CustomHighlightRules;
var Mode = function() {
this.HighlightRules = CustomHighlightRules;
};
oop.inherits(Mode, TextMode);
(function() {
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/custom_highlight_rules', [], function(require, exports, module) {
var oop = require("ace/lib/oop");
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var CustomHighlightRules = function() {
var keywordMapper = this.createKeywordMapper({
"variable.language": "this",
"keyword": "Mark|Ben|Bill",
"constant.language": "true|false|null",
// it is also possible to use css, but that may conflict with themes
"customTokenName": "problem"
}, "text", true);
this.$rules = {
"start": [
{
regex: "\\w+\\b",
token: keywordMapper
},
]
};
this.normalizeRules()
};
oop.inherits(CustomHighlightRules, TextHighlightRules);
exports.CustomHighlightRules = CustomHighlightRules;
});
var editor = ace.edit("editor");
editor.session.setMode("ace/mode/custom");
var someString = 'Mark has solved the problem';
editor.session.setValue(someString);
</script>
</body>
</html>

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>

Adding Multiple Markers to Google Maps v3 from JSON

I've been trying to make a web app that shows multiple markers on google maps. I tried using this tutorial and the code works fine until I get to the point where I need to get the JSON data from the server instead of using the example JSON data in the same js file as the code.
I try to save the ajax response into variable but i get this error
TypeError: json is null
[Break On This Error]
for (var i = 0, length = json.length; i < length; i++) {
And this is the code I am using.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(57.9, 14.6),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://myurl.com/getdata",
'dataType': "json",
'success': function (data) {
json = data; } });
return json;})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
var infoWindow = new google.maps.InfoWindow();
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
// Creating a closure to retain the correct data
//Note how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>

how to use the Dojo code in Enyo..?

I'm a new developer in Enyo(TouchPad). I would like to develop an app consisting some charts in it. so I'm trying to use Dojo framework libraries in Enyo.
Can anyone please help me in how to include the dojo code my application.
I'm posting my code, please have a look.
INDEX.HTML :
<!doctype html>
<html>
<head>
<title>Canvas Demo</title>
<script src="../../../../1.0/framework/enyo.js" type="text/javascript"></script>
<script src="lib/widget/Chart2D.js" type="text/javascript"> </SCRIPT>
<script src="lib/chart2D.js" type="text/javascript"> </SCRIPT>
<script src="lib/tom.js" type="text/javascript"> </SCRIPT>
</head>
<body>
<script type="text/javascript">
enyo.create({kind: "CanvasDemo"}).renderInto(document.body);
</script>
</body>
</html>
.Js file ::
enyo.kind({
name: "CanvasDemo",
kind: enyo.Control,
nodeTag: "canvas",
domAttributes: {
width:"300px",
height:"300px",
style: "border: 2px solid #000;"
},
// After the canvas is rendered
rendered: function() {
// I want to place the dojo code here to display a chart in the canvas.
}
});
DOJO CODE ::
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.Tom');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
var chart2 = new dojox.charting.Chart2D('chart2').
setTheme(dojox.charting.themes.Tom).
addPlot('default', {type: 'Pie', radius: 70, fontColor: 'black'}).
addSeries('Visits', chartData).
render();
var anim = new dojox.charting.action2d.MoveSlice(chart2, 'default');
chart2.render();
});
Please help me in how to modify the dojo code ,so that it can work in the enyo..
Thanks in Advance.
Regards,
Harry.
index.html :
<!doctype html>
<html>
<head>
<title>dojo</title>
<script src="C:\WebOs\Development\enyo\1.0\framework\enyo.js" type="text/javascript"></script>
<script type="text/javascript" src="C:\Users\pangulur\Downloads\dojo-release-1.6.1-src\dojo-release-1.6.1-src\dojo\dojo.js"></script>
/head>
<body>
<script type="text/javascript">
new enyo.Canon.graphs2().renderInto(document.body);
</script>
</body>
</html>
Source/Charts1.js :
enyo.kind({
name: "enyo.Canon.graphs2",
kind: enyo.Control,
components: [
{kind: "PageHeader", content: "bargraph"},
//{style: "padding: 10px", content: "Note: In the browser, you can press ctrl-~ to display the app menu."},
{kind: "Button", caption: "display graph", onclick: "displayGraph", flex: 1},
],
displayGraph: function() {
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.PlotKit.green');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
//create / swap data
var barData = [];
dojo.forEach(chartData,function(item) { barData.push({ x: item['y'], y: item['x'] }); });
var chart1 = new dojox.charting.Chart2D('chart1').
setTheme(dojox.charting.themes.PlotKit.green).
addAxis('x', { fixUpper: 'major', includeZero: false, min:0, max:6 }).
addAxis('y', { vertical: true, fixLower: 'major', fixUpper: 'major' }).
addPlot('default', {type: 'Columns', gap:5 }).
addSeries('Visits For February', chartData, {});
var anim4b = new dojox.charting.action2d.Tooltip(chart1, 'default');
var anim4c = new dojox.charting.action2d.Shake(chart1,'default');
chart1.render();
// var legend4 = new dojox.charting.widget.Legend({ chart: chart1 }, 'legend3');
});
}
});
Here I'm not sure about how to call the dojo code in enyo.
and
depends.js :
enyo.depends(
"source/charts1.js",
"lib/Chart2D.js",
"lib/widget/Chart2D.js",
"lib/blue.js",
"lib/dojo.js"
);
Now I'm getting the following errors :
error: Uncaught ReferenceError: dojo is not defined, Chart2D.js:1
[20110818-09:33:13.136736] error: Uncaught ReferenceError: dojo is not defined, widget/Chart2D.js:1
[20110818-09:33:13.138227] error: Uncaught ReferenceError: dojo is not defined, blue.js:1
[20110818-09:33:13.150707] error: Uncaught TypeError: Cannot read property 'graphs2' of undefined, index.html:10
It is working fine when I use it as a .HTML file with the same code in browser.
Chart.html :
<html>
<head>
<title>dojo</title>
<script type="text/javascript" src="C:\Users\pangulur\Downloads\dojo-release-1.6.1- src\dojo-release-1.6.1-src\dojo\dojo.js"></script>
</head>
<body>
<div id="chart1" style="width:260px;height:200px;"></div>
<script>
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.PlotKit.green');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
//create / swap data
var barData = [];
dojo.forEach(chartData,function(item) { barData.push({ x: item['y'], y: item['x'] }); });
var chart1 = new dojox.charting.Chart2D('chart1').
setTheme(dojox.charting.themes.PlotKit.green).
addAxis('x', { fixUpper: 'major', includeZero: false, min:0, max:6 }).
addAxis('y', { vertical: true, fixLower: 'major', fixUpper: 'major' }).
addPlot('default', {type: 'Columns', gap:5 }).
addSeries('Visits For February', chartData, {});
var anim4b = new dojox.charting.action2d.Tooltip(chart1, 'default');
var anim4c = new dojox.charting.action2d.Shake(chart1,'default');
chart1.render();
var legend4 = new dojox.charting.widget.Legend({ chart: chart1 }, 'legend3');
});
</script>
</body>
</html>
Please help me in working with this in Enyo.
Thanking You.
Kind Regards,
Harry.
I don't think you have to modify the Dojo code. In Enyo, you have to tell the framework where it has to look for included JS files. Yo do so editing the depends.js file.
The index.html:
<!doctype html>
<html>
<head>
<title>Canvas Demo</title>
<script src="../../../../1.0/framework/enyo.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
new enyo.Canon.graphs2().renderInto(document.body);
</script>
</body>
</html>
and depends.js:
enyo.depends(
"lib/dojo/dojo.js" ,
"source/charts1.js"
);
You'll have to copy everything Dojo needs to work (dojo, dojox, dijit) into lib, and check enyo paths.
I get a Dojo error when creating the new Chart2D object, and I'm not a Dojo expert to fix this. It's in the line:
var chart1 = new dojox.charting.Chart2D("simplechart");
I've modified your code:
enyo.kind({
name: "enyo.Canon.graphs2",
kind: enyo.Control,
components: [
{kind: "PageHeader", content: "bargraph"},
//{style: "padding: 10px", content: "Note: In the browser, you can press ctrl-~ to display the app menu."},
{kind: "Button", caption: "display graph", onclick: "displayGraph", flex: 1},
],
displayGraph: function() {
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.PlotKit.green');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
//create / swap data
var barData = [];
dojo.forEach(chartData,function(item) { barData.push({ x: item['y'], y: item['x'] }); });
var chart1 = new dojox.charting.Chart2D("simplechart"); // HERE IS THE PROBLEM
chart1.setTheme(dojox.charting.themes.PlotKit.green);
chart1.addAxis('x', { fixUpper: 'major', includeZero: false, min:0, max:6 });
chart1.addAxis('y', { vertical: true, fixLower: 'major', fixUpper: 'major' });
chart1.addPlot('default', {type: 'Columns', gap:5 });
chart1.addSeries('Visits For February', chartData, {});
var anim4b = new dojox.charting.action2d.Tooltip(chart1, 'default');
var anim4c = new dojox.charting.action2d.Shake(chart1,'default');
chart1.render();
// var legend4 = new dojox.charting.widget.Legend({ chart: chart1 }, 'legend3');
});
}
});
The object doesn't get instantiated. Got null pointer :-(

Resources