Getting Data points for canvasjs from a text file - javascript

Im trying to make a chart that dynamically gets plot values from a .txt file.
Here i can produce a simple chart with canvasjs this is the exact kind of chart i need to make except for it should get x values from a .txt file dynamically.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Percents",
fontFamily: "Impact",
fontWeight: "normal"
},
legend:{
verticalAlign: "bottom",
horizontalAlign: "center"
},
data: [
{
//startAngle: 45,
indexLabelFontSize: 20,
indexLabelFontFamily: "Garamond",
indexLabelFontColor: "darkgrey",
indexLabelLineColor: "darkgrey",
indexLabelPlacement: "outside",
type: "doughnut",
showInLegend: true,
dataPoints: [
{ y: 55, legendText:"55%", indexLabel: "55%" },
{ y: 45, legendText:"45%", indexLabel: "45%" },
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
Here i try but it fails
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="jquery.canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var dataPoints = [];
//Replace text file's path according to your requirement.
$.get("MYFILE.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({x: x , y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
chart.render();
});
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
It doesnt even give me any errors to debug.
EDIT: Content of .TXT file is very simple
MYFILE.txt
56

As this code, where I only replaced the ajax request by hardcoded data, is working, it has to be a problem with the ajax request itself.
var dataPoints = [];
(function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
dataPoints.push({x: x , y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
chart.render();
})("1\n2\n4\n3");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
As we found out in the comments, it is as I assumed, that you are trying to run the files from the file system via file:/// in your browser, instead of a (local) web server, but ajax requests are not executable in this environment for security reasons.

Related

Chart.js Chart does not start at

I want to that the Chart start at 0. But it takes always the lower value to start.
I already tried a few things but nothing works.
It never takes the settings done in de options Part of de javascript part. So i dont know what the issue is. It never starts at 0. But this is what i want to.
Please help. Thank you very much :)
Looks currently like this: https://school.luis-luescher.com/m242/moin/index.php
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<style type="text/css">
BODY {
width: 550PX;
}
#chart-container {
width: 100%;
height: auto;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
</head>
<body>
<div id="chart-container">
<canvas id="graphCanvas"></canvas>
</div>
<script>
$(document).ready(function() {
showGraph();
});
function showGraph() {
{
$.post("https://school.luis-luescher.com/m242/moin/data.php",
function(data) {
console.log(data);
var trytime = [];
var count = [];
for (var i in data) {
trytime.push(data[i].trytime);
count.push(data[i].count);
}
var chartdata = {
labels: trytime,
datasets: [{
label: 'Erfolgreiche Authentifizerungen',
backgroundColor: '#8846f1',
borderColor: '#a446f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
borderWidth: 1,
data: count,
}],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata
});
});
}
}
</script>
</body>
</html>
Your Options object must be outside chartData.
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
options: options
});

Jquery vs. pure javascript, why does my code not work? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
I am new to Javascript and ran into a problem I can't resolve.
I wanted to rewrite an example with jquery into pure Javascript.
I don't understand why this doesn't work.
Why is the variable "vorlauf" empty outside the function?
Isn't it a global variable?
I attached a picture of the console output.
Not working as expected (tried to omit every clutter...):
<!DOCTYPE HTML>
<html>
<head>
<script>
let vorlauf = new Array();
let getJSON = function (name) {
fetch(name + ".json")
.then(response => response.json())
.then(parsed => {
console.log(parsed.length, parsed)
for (let i = 0; i < parsed.length; i++) {
vorlauf.push({
x: new Date(parsed[i].date + " " + parsed[i].time),
y: Number(parsed[i].temp) / 1000
})
}
});
}
getJSON("vorlauf")
console.log("Nach Aufruf getJSON " + vorlauf.length)
</script>
</head>
<body>
</body>
</html>
Works as expected (included everything):
!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX:{
valueFormatString: "YYYY-MM-DD hh:mm:ss" ,
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for(let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
The json data:
[{"date": "2020-02-22", "temp": "39937", "time": "09:28:59"}, {"date": "2020-02-22", "temp": "39937", "time": "09:29:21"}]
picture of the debug output of Firefox
Please place all javascript above .
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX: {
valueFormatString: "YYYY-MM-DD hh:mm:ss",
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for (let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>

CanvasJs chart using json data

I am trying to draw CanvasJs chart using data from json file but for some reason it does not work.
The data which I am trying to display are data which is in json file represented as number "####" and value "#"
Please take a look at the code below.
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Year(data[i].date),
y: data[i].value
});
}
chart.render();
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", addData);
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to call the json, $.getJson gives a callback, so once the api gives the data you need to create the dataPoints, once its created create the chart.
I hope the below solution will solve the issue.
Note: If required you can add a loader for the mean time while its loading , so the user will know that some thing is loading
const chartCreation = (data) => {
$("#chartContainer").CanvasJSChart({
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
}
let dataPoints = [];
const addData = (data) => {
dataPoints = data[1].filter(obj => +(obj.date) >= 2010 && +(obj.date) <=2018
).map(obj => ({x: +(obj.date),
y: obj.value ? obj.value : 0}))
// once we have the data pass it to chart creation
// function
chartCreation(dataPoints);
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", (data) =>{
// pass the data to function
addData(data);
});
return{
}
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Updated
As per the comment, first you can array.filter , once you filter you will get a new array where you can return the properties whatever that you want. using array.map to return what ever the properties.

How to call a php file to canvasjs

First time poster, and still relatively new to javascript... I am trying to figure out how to reflect information from a php file to a canvasjs file.
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 60, x: 2 },
]
},
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 0, x: 2 },
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Instead of the labels and datapoints etc, I want information from a php file (or how to do it to any type of file) to be collected then displayed into this canvasjs file.
Is there a way to do this?
Sorry if I'm not clear, I really appreciate any help I can get :)
Thanks!
One way would be to make the file you pasted a PHP file, then use PHP in it:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
?>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
},
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Another way would be to create a PHP file that returns the data, and make an AJAX request:
data.php:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
echo json_encode($dataPoints);
ui.html:
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var request = new XMLHttpRequest();
request.onload = function () {
var dataPoints = JSON.parse(request.responseText);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: dataPoints
},
{
type: 'line',
dataPoints: dataPoints
}
]
});
chart.render();
};
request.open('GET', 'data.php', true);
request.send();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>

Why this Javascript Chart won't work twice?

I've got some charts of http://canvasjs.com/javascript-charts/ and they are just wonderful! I used one of them and it worked perfectly :
<script type="text/javascript">
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['ip', 'quantity'],
#foreach($ipsWithBytesDates as $item)
['{{$item['ip']}}', {{$item['counts']}}],
#endforeach
]);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
<div id="piechart_3d" style="width: 700px; height: 350px;"></div>
Now i need a second chart - I've already got it from the website and copy & paste it in my code.. but this haven't worked like I want.. the second chart works but overwrites the whole first chart.
The first chart is a column chart and is at the top of my page.. the second chart should be at the bottom.. but it isn't, it every time just overwrites my first chart -- could anybody tell me why? I think it's because of the "window.onload" at the beginning of both chart.. but I haven't really worked with javascript.
second chart:
<script type="text/javascript">
window.onload = function () {
var secchart = new CanvasJS.Chart("chartContainer2",
{
title:{
text: "U.S Smartphone OS Market Share, Q3 2012",
fontFamily: "Impact",
fontWeight: "normal"
},
legend:{
verticalAlign: "bottom",
horizontalAlign: "center"
},
data: [
{
//startAngle: 45,
indexLabelFontSize: 20,
indexLabelFontFamily: "Garamond",
indexLabelFontColor: "darkgrey",
indexLabelLineColor: "darkgrey",
indexLabelPlacement: "outside",
type: "doughnut",
showInLegend: true,
dataPoints: [
{ y: 53.37, legendText:"Android 53%", indexLabel: "Android 53%" },
{ y: 35.0, legendText:"iOS 35%", indexLabel: "Apple iOS 35%" },
{ y: 7, legendText:"Blackberry 7%", indexLabel: "Blackberry 7%" },
{ y: 2, legendText:"Windows 2%", indexLabel: "Windows Phone 2%" },
{ y: 5, legendText:"Others 5%", indexLabel: "Others 5%" }
]
}
]
});
secchart.render();
}
</script>
<script type="text/javascript"></script>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>
source code from the chartlibary:
You need to have separate containers for each chart. Each snippet you've pasted is using var chart = new CanvasJS.Chart("chartContainer",
Try setting the 2nd chart to use a different element on your page.
<div id="chartContainer1" style="height: 300px; width: 100%;"></div>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>
var chart = new CanvasJS.Chart("chartContainer1", ...
var chart = new CanvasJS.Chart("chartContainer2", ...
Looks like both of these charts are being rendered in an element called "chartContainer". In both code snippets there is a div at the bottom with this name. You should change the name of this div for at least one of the charts.

Categories