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

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>

Related

Line from Chart.js in C# asp.net mvc does not work

I'm having a problem with C# asp.net mvc. The line in my chart is not getting displayed. I tried many different charts but it's not working. The objective is using my database values to draw the line.
My View: Estatisticas.cshtml
#model Estágio_TP.Models.Alerta
#{
ViewBag.Title = "Estatisticas";
}
<h2>Estatisticas de #Html.DisplayFor(model => model.nomeAlerta)</h2>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<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/canvasjs.min.js"></script>
<title>Doughnut Chart</title>
<meta name="viewport" content="width=device-width" />
<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/canvasjs.min.js"></script>
<title>Gráfico Chart</title>
<script src="~/Content/js/Chart_est.js"></script>
</head>
<body>
<div id="chartContainer1" style="width: 100%; height: 500px;display: inline-block;"></div>
<br /><br /><br />
<div id="chartContainer2" style="width: 100%; height: 500px;display: inline-block;"></div>
<!--<div class="card-body">
<div class="chart-area">
<canvas id="teste_est"style="width: 100%; height: 500px;display: inline-block;"></canvas>
</div>
</div>-->
<script type="text/javascript">
function chart1(){
var chart1 = new CanvasJS.Chart("chartContainer1", {
title: {
text: " #Html.DisplayFor(model => model.nomeTrigger)"
},
animationEnabled: true,
legend: {
fontSize: 20,
fontFamily: "Helvetica"
},
theme: "light2",
data: [
{
type: "doughnut",
indexLabelFontFamily: "Garamond",
indexLabelFontSize: 20,
indexLabel: "{label} {y}%",
startAngle: -20,
showInLegend: true,
toolTipContent: "{legendText} {y}%",
dataPoints: [
{ y: #ViewData["valor"], legendText: "Em Uso", label: "Em Uso"
},
{ y: 100 - #ViewData["valor"], legendText: "Livre", label: "Livre" },
],
//dataPoints: #Html.Raw(ViewBag.DataPoints),
}
]
});
chart1.render();
}
$(document).ready(function () {
showChart3();
});
function showChart3() {
$.get("/alertas/json/", function (data) {
var tempo = [];
var valor = [];
for (var i in data) {
tempo.push(data[i].tempo);
valor.push(data[i].valor);
}
var chart = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
theme: "light2",//light1
title: {
text: "Gráfico ao Longo do Dia"
},
data: [
{
// Change type to "bar", "splineArea", "area", "spline", "pie",etc.
type: "line",
dataPoints: data
}
]
});
chart.render();
});
}
function start() {
chart1();
showChart3();
}
window.onload = start();
</script>
<!-- <script src="~/Content/js/teste_estatistica.js"></script>-->
</body>
</html>
Controller:
public ContentResult JSON(string id)
{
var teste_xx = db.Conteudos.Where(a => a.nomeAl == id)
.Where(a => a.Data_cont.Day == DateTime.Now.Day)
.OrderBy(a => a.Data_cont)
.Select(a => new
{
valor = a.max_valor,
tempo = a.Data_cont //.ToString("hh:mm")
});
List<DataPoint> dataPoints;
dataPoints = new List<DataPoint>();
foreach (var result in teste_xx)
{
//list2.Add(result.tempo.ToString());
//list2.Add(result.valor.ToString());
var tempo = result.tempo;
var valor = result.valor;
dataPoints.Add(new DataPoint(tempo, valor));
}
JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
return Content(JsonConvert.SerializeObject(dataPoints, _jsonSetting), "application/json");
}
}
DB: Only need the DateTime("hh:mm:ss") and the max_value
Database
There are many problems that they should be modified.
You import canvasjs.min.js twice... just import 1 time.
I only solve your Alertas/Json action, I have no Alertas/Estatisticas's model Estágio_TP.Models.Alerta so the page will not show chartContainer1's solution.
I modify the Json action to return JsonResult. Not ContentResult.
Your Alertas/Json should take one Id parameter, so I hard-code the parameter in the $.get("/alertas/json/1");
I assume some simple db data to show this chart will work.
Assign axisX's properties, including the time format/intervals
Assing dataPoints with x and y as keys, not your tempo and valor as keys.
My version works:
Estatisticas.cshtml
<div id="chartContainer2" style="width: 100%; height: 500px;display: inline-block;"></div>
#section scripts {
<script>
$(document).ready(function () {
showChart3();
});
function showChart3() {
$.get("/alertas/json/1", function (data) {
var dataPoints = [];
for (var i in data) {
dataPoints.push({
x: new Date(parseInt(data[i].tempo.replace("/Date(", "").replace(")/", ""), 10)),
y: data[i].valor
});
}
console.log(dataPoints);
var chart = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
theme: "light2",
title: {
text: "Gráfico ao Longo do Dia"
},
axisX: {
interval: 10,
intervalType: "minute",
valueFormatString: "YYYY/MM/DD HH:mm"
},
data: [
{
type: "line",
dataPoints: dataPoints
}
]
});
chart.render();
});
}
</script>
}
Controller
public JsonResult JSON(string id)
{
var db = new List<Conteudos>()
{
new Conteudos()
{
Data_cont = DateTime.Now,
max_valor = 10,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(1),
max_valor = 40,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(2),
max_valor = 30,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(3),
max_valor = 50,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(4),
max_valor = 60,
nomeAl = "1"
}
};
var teste_xx = db.Where(a => a.nomeAl == id)
.Where(a => a.Data_cont.Day == DateTime.Now.Day)
.OrderBy(a => a.Data_cont)
.Select(a => new
{
valor = a.max_valor,
tempo = a.Data_cont //.ToString("hh:mm")
});
List<DataPoint> dataPoints;
dataPoints = new List<DataPoint>();
foreach (var result in teste_xx)
{
//list2.Add(result.tempo.ToString());
//list2.Add(result.valor.ToString());
var tempo = result.tempo;
var valor = result.valor;
dataPoints.Add(new DataPoint(tempo, valor));
}
return Json(dataPoints, JsonRequestBehavior.AllowGet);
}

How to get x-axis value in chart as string?

I am trying to plot a graph using chart.js where y-axis values are numbers and x-axis values are strings. I have given the code that i have written, but it does not plot the string values.
Appreciate your help.
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
x: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" 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>
</html>
For your case you should supply label property not x value and also i believe you should use column charts for this purpose.
You might see some labels not showing up.You can either set the angle or increase the width of chart to make it visible.
Try running this snippet
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
axisX: {
labelAngle: 180
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
label: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" 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>
</html>

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.

Getting Data points for canvasjs from a text file

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.

Dyanamic highchart with csv/txt input file

I am new on highchart. I have gone through the help portal of this and I am unable to fulfill my requirement so need you help/guide to complete this task .
My task is to read the data from a csv/TXT file which contains TPS details as per below format and show it on a dynamic running chart ( it's ok if the chart will refresh in one minute ) .
DATA format:
16:08:02,3
16:08:04,5
16:08:05,1
16:09:01,10
The above file is appending on every second , will read the last one minute data from file and plot this on chart .
I have tried this using below code. Don't know what I am missing.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>TPS Example</title>
<script type="text/javascript" src="C:/Backup/SUNIL/Software/library/jquery-2.2.0.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'TPS Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 3,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
</script>
</head>
<body>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<div id="container" style="min-width: 50px; height: 200px; margin: 0 auto"></div>
</body>
</html>
You probably have incorrect paths to your script files.
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
The code works fine: http://jsfiddle.net/tmp3pty2/

Categories