Fill CanvasJS with json - javascript

Currently I am trying to create a chart for the first time using javascript.
I want to show the data on the screen by using the fill chart json method in the mainpage page.
When I check the url in json format, output looks like below.
[
{
"CV_STATU":"Reddedildi",
"MyCount":366
},
{
"CV_STATU":null,
"MyCount":23
},
{
"CV_STATU":"Görüşmeye Bekleniyor",
"MyCount":14
}
]
but when I call the mainpage(localhost:56569/Yonetim/Home/MainPage), nothing is displayed.
public class HomeController : Controller
{
public ActionResult MainPage()
{
var model = new CvViewModel();
return View(model);
}
public JsonResult FillChart()
{
using (MULAKATDBEntities1 ent = new MULAKATDBEntities1())
{
var dbStatuList = ent.CV.GroupBy(x => new { x.CV_STATU }).Select(g => new { g.Key.CV_STATU , MyCount = g.Count() }).ToList();
return Json(JsonConvert.SerializeObject(dbStatuList), JsonRequestBehavior.AllowGet);
}
}
}
my javascript code is as follows :
<html>
<head>
<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>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"/>
</body>
</html>
<script type="text/javascript">
window.onload()=function(){
var dataPoints = [];
$.getJSON("Yonetim/Home/FillChart", function (data) {
for (var i = 0; i <= data.length - 1; i++) {
dataPoints.push({ label: data[i].CV_STATU, y: parseInt(data[i].MyCount) });
}
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
title: {
text: "CanvasJS Charts "
},
data: [
{
type: "column",
dataPoints: dataPoints
}
]
});
chart.render();
});
}
</script>
How can I create a chart with cv_statu and mycount information on the screen?

Here is a working solution:
<html>
<head>
<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>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;" ></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("https://79723e01-80d8-4331-ad9f-5ec9b34a6857.mock.pstmn.io/Yonetim/Home/FillChart", function (data) {
const dataPoints = data.map(point => {
return {
label: point.CV_STATU,
y: parseInt(point.MyCount),
}
})
const chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
title: {
text: "CanvasJS Charts"
},
data: [
{
type: "column",
dataPoints: dataPoints
}
]
});
chart.render();
})
})
</script>
You need to change the url in $.getJSON to yours. Mine will work only if you launch your page as a server.

Related

How do you call a python api or local data into the js lib google.visualization.DataTable()?

I have been working for 2 weeks to try and get a CSV file (local) To load google.visualization.DataTable(). Or I would love to Us Ajax to call a Python flask API I created. I would like to create a Gantt chart dynamically.
My code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function daysToMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}
function drawChart() {
var jsonData = $.ajax({
url: "http://127.0.0.1:5042/crudSEapi/D3test",
dataType: "json",
async: false
}).responseText;
var jsonData = JSON.parse(jsonData);
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Create our data table out of JSON data loaded from server.
console.log(jsonData["Column 0"])
data.addColumn('string',jsonData["Column 0"]);
data.addColumn(jsonData["Column 1"][1], jsonData["Column 1"][0]);
data.addRows([
[jsonData["Column 1"][2]]
]);
// Instantiate and draw our chart, passing in some options.
var options = {
height: 275,
gantt: {
criticalPathEnabled: false, // Critical path arrows will be the same as other arrows.
arrow: {
angle: 100,
width: 5,
color: 'green',
radius: 0
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.Gantt(container);
// throw error for testing
google.visualization.events.addListener(chart, 'ready', function () {
throw new Error('Test Google Error');
});
// listen for error
google.visualization.events.addListener(chart, 'error', function (err) {
// check error
});
chart.draw(data, options);
}
</script>
<main id="main">
<section id="data-section">
<h2>Data Input</h2>
<div id="data"></div>
</section>
</main>
<h2>chart output</h2>
<div id="chart_div"></div>
<script>
function apicall(url) {
$.ajax({
type:"POST", url:url,
success: (data) => { $("#data").html(data); }
});
}
window.onload = function () {
apicall("http://127.0.0.1:5042/crudSEapi/D3test");
}
</script>
No mater how many YouTube videos I watch, I can't understand how to do an Ajax call from my Python Flask API AND load the needed data to google.visualization.DataTable() for dynamic creation of a Gantt chart:) please help
really my issue is a lack of Mastery of JS. How do I import data from API or a Local CSV? How do I Parse the data, then Organize the data to be used in google.visualization.DataTable(). I wish I could find a simple example. please help...
My Python Flask Api Code:
import json
#crudSEapi.route("/D3test", methods=["GET", "POST"])
def d3():
df = pd.read_csv("SkillBook/static/Sheet4.csv")
chartdata = df.to_json()
data = json.dumps(chartdata, indent=2)
print(data)
return Response(data)
CSV file:
id,title,start,end,dependencies,completed
m1,milestone 1,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),m2: start-to-start,0.6
m2,milestone 2,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),[m3: end-to-start,m4: end-to-end],0
m3,milestone 3,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),,0.75
m4,milestone 4,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),,0.2
the output should look like this:
I figured it out thanks to #WhiteHat.
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://unpkg.com/jquery-csv#1.0.21/src/jquery.csv.js"></script>
<div id="chart_div"></div>
<li><input></li>
<li><input></li>
<li><input></li>
<button>update data in chart</button>
<button>print SVG</button>
<script>
function toMilliseconds(minutes) {
return minutes * 60 * 1000;
}
google.charts.load('current', {
callback: function () {
$.get("/static/Sheet4.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
console.log(arrayData[6][1])
var data = new google.visualization.DataTable();
data.addColumn(arrayData[2][1], arrayData[1][1]);
data.addColumn(arrayData[2][2], arrayData[1][2]);
data.addColumn(arrayData[2][4], arrayData[1][4]);
data.addColumn(arrayData[2][5], arrayData[1][5]);
data.addColumn(arrayData[2][6], arrayData[1][6]);
data.addColumn(arrayData[2][7], arrayData[1][7]);
data.addColumn(arrayData[2][8], arrayData[1][8]);
data.addRows([
[
arrayData[3][1],
arrayData[3][2],
null,
null,
toMilliseconds(5),
100,
null,
],
[
arrayData[4][1],
arrayData[4][2],
null,
null,
toMilliseconds(70),
100,
null,
],
[
arrayData[5][1],
arrayData[5][2],
null,
null,
toMilliseconds(10),
100,
arrayData[3][1],
],
[
arrayData[6][1],
arrayData[6][2],
null,
null,
toMilliseconds(45),
75,
arrayData[5][1],
],
[
arrayData[7][1],
arrayData[7][2],
null,
null,
toMilliseconds(10),
0,
arrayData[6][1],
],
[
arrayData[8][1],
arrayData[8][2],
null,
null,
toMilliseconds(2),
0,
arrayData[5][1],
],
]);
var options = {
height: 275,
gantt: {
criticalPathEnabled: false, // Critical path arrows will be the same as other arrows.
arrow: {
angle: 100,
width: 5,
color: 'green',
radius: 0
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.Gantt(container);
chart.draw(data, options);
});
},
packages: ['gantt']
});
</script>
And my CSV:
step0,step1,step2,step3,step4,step5,Step6,step7,step8
Purpose,Task ID,Task Name,Resource ID,Start,End,Duration,Percent Complete,Dependencies
Data Type,string,string,string,date,date,number,number,string
Prject1data1,Test1,test1x,test1y,test1z,0,1,2,test1a
Prject1data2,Test2,test2x,test2y,test2z,0,1,2,test2a
Prject1data3,Test3,test3x,test3y,test3z,0,1,2,test3a
Prject1data4,Test4,test4x,test4y,test4z,0,1,2,test4a
Prject1data5,Test5,test5x,test5y,test5z,0,1,2,test4a
Prject1data6,Test6,test6x,test6y,test6z,0,1,2,test4a
Prject1data7,Test7,test7x,test7y,test7z,0,1,2,test4a
Next step:
Change Input To dynamic. I will create inputs form on website to change the data
I will allow CSV to be upload and parsed no mater the size of the CSV file

Adding data in node of jstree through dropdown not working properly

I am trying to add a dropdown in a node and want to be able to create and remove the nodes. I am able to do that but whenever i create/remove a node the dropdown values that i have selected are removed from where the node is created or removed. I am using select2 for dropdown if that helps.
below is the link for demonstration
https://www.arsallodhi.com/jstree/index.html
thanks in advance
I think redraw method is called which does removes the values. So i tried to catch it but couldnt.
<html>
<head>
<style>
.jstree-default .jstree-node, .jstree-leaf {
min-height: 35px !important;
}
.jstree-open .jstree-node {
padding-top: 15px !important;
}
</style>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css"/>
</head>
<body>
<div id="jstreee">
<ul>
<li class="jstree-open">
Organization
</li>
</ul>
</div>
<script src="https://kendo.cdn.telerik.com/2019.2.514/js/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script>
function formatDropdown1(option) {
if (option.id) {
return option.text;
} else {
return '';
}
};
function addTagValueClass() {
$('.tag').select2({
placeholder: '',
allowClear: true,
tags: true,
templateSelection: formatDropdown1,
});
}
var counter = 0;
function customMenu2(node) {
var position = 'inside';
var parent;
var selected_id;
selected_id = parent = $('#jstreee').jstree('get_selected');
counter++;
var node_data;
node_data = "<li class='node-li'><select data-live-search='true' class='tag' placeholder='Tag'><option></option><option value='volvo'>Project</option><option value='saab'>Owner</option><option value='mercede'>Department</option><option value='audi'>Business Unit</option></select></li>"
var items = {
createItem: {
label: "Add Node",
action: function () {
$('#jstreee').jstree().create_node(parent, {"id": "ajson5" + counter, "text": node_data}, position
, function () {
addTagValueClass();
$('#jstreee').jstree().open_node('#' + parent);
});
}
},
deleteItem: {
label: "Remove Node",
action: function () {
if (selected_id != "j1_1") {
$('#jstreee').jstree().delete_node(selected_id);
addTagValueClass();
}
}
}
};
return items;
}
$('#jstreee').on('open_node.jstree', function (e, data) {
addTagValueClass();
});
$('#jstreee').jstree({
"core": {"check_callback": true, "themes": {"icons": false}, "toggle_node": true}, // so that modifying operations work
"plugins": ["contextmenu"], contextmenu: {items: customMenu2}
});
</script>
</body>
</html>
I want that the values which i have set through the dropdown remain even when a node is created or removed.

How to load external JSON data via an ajax call on html page?

I created a dummy JSON file below to test out whether this html page works. How do I load the data via ajax request? The only error I got is
Uncaught ReferenceError: data is not defined.
How do I call this JSON file in my html page? Been trying but to no avail. Got this from view-source if it helps
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Matter Timeline</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<!-- load handlebars for templating, and create a template -->
<script src="dist/handlebars-v4.0.11.js"></script>
<script id="item-template" type="text/x-handlebars-template">
{{target}}
<font color="#229954"><b>{{status_green}}</b></font>
<font color="#A93226"><b>{{status_red}}</b></font>
<br/>
<font size="2" color="#2874A6">{{action}}</font>
<font size="2" color="#2874A6"><i>{{user}}</i></font> <br/>
<span class="tooltip-date">{{datetime}}</span>
</script>
<script src="dist/vis.js"></script>
<link href="dist/vis-timeline-graph2d.min.css" rel="stylesheet" type="text/css" />
<script>
function resettimeline() {
document.location.reload();
};
</script>
</head>
<body>
<p>
<center><h2>Matter Timeline</h2></center>
</p>
<div id="visualization"></div>
<script type="text/javascript">
var groups = new vis.DataSet([
{id: 0, content: 'Process/Task', value: 1},
{id: 1, content: 'Req/Matter/Doc', value: 2}
]);
var source = document.getElementById('item-template').innerHTML;
var template = Handlebars.compile(document.getElementById('item-template').innerHTML);
$.ajax({
url: 'http://127.0.0.1:8887/data.json',
dataType: "json",
success: function(data) {
//handle you data here
}
});
// create visualization
var container = document.getElementById('visualization');
var options = {
// option groupOrder can be a property name or a sort function
// the sort function must compare two groups and return a value
// > 0 when a > b
// < 0 when a < b
// 0 when a == b
groupOrder: function (a, b) {
return a.value - b.value;
},
orientation: {
axis: 'top',
item: 'top'
},
height: "85vh",
template: template
//timeAxis: {scale: 'day', step:3}
};
var timeline = new vis.Timeline(container);
timeline.setOptions(options);
timeline.setGroups(groups);
timeline.setItems(data);
timeline.on('doubleClick', function (properties) {
window.open('the_doc_url',
'newwindow',
'width=1000,height=600');
return false;
});
</script>
<br/>
Fit to Width
</body>
</html>
data.json
{
"data": [
{
id: 1, group: 0,
target: 'Request',
action: 'from',
user: 'SAS',
datetime: '7/10',
title: '<span class="tooltip-date">Date: 7/10/2017 09:00</span><br/>Req ID: R123',
start: new Date(2017,9,7, 9,0,0,0)
},
{
id: 2, group: 0,
target: 'Request',
action: 'by',
user: 'Alice',
datetime: '8/10',
title: '<span class="tooltip-date">Date: 8/10/2017 13:34</span><br/>Req ID: R123',
start: new Date(2017,9,8, 12,30,0,0)
}
]
}
AJAX means "Asynchronous JavaScript And XML", and it seems that you missed the asynch part. The code that is using the "data" variable is outside the callback, then this variable doesn't exist (or its value is undefined).
You need to use the json data after receiving it, something like this (it could probably be cleanup a little bit):
$.ajax({
url: 'http://127.0.0.1:8887/data.json',
dataType: "json",
success: function(data) {
//handle you data here
// create visualization
var container = document.getElementById('visualization');
var options = {
// option groupOrder can be a property name or a sort function
// the sort function must compare two groups and return a value
// > 0 when a > b
// < 0 when a < b
// 0 when a == b
groupOrder: function (a, b) {
return a.value - b.value;
},
orientation: {
axis: 'top',
item: 'top'
},
height: "85vh",
template: template
//timeAxis: {scale: 'day', step:3}
};
var timeline = new vis.Timeline(container);
timeline.setOptions(options);
timeline.setGroups(groups);
timeline.setItems(data.data);
timeline.on('doubleClick', function (properties) {
window.open('the_doc_url',
'newwindow',
'width=1000,height=600');
return false;
});
}
});

How to transfer XML view to JavaScript view / SAPUI5

Im trying to trasnform xml BlockLayout structured code to js. But it doesnt work properly, because it doesnt show any content on view. I checked the aggregations and I see there is cell aggregation for Row and sap.ui.Control aggregation for cell.
JavaScript:
var oLayout = new sap.ui.layout.VerticalLayout("Layout", {
content: [
new sap.ui.layout.BlockLayout("Block", {
content: [
new sap.ui.layout.BlockLayoutRow("Row", {
content: [
new sap.ui.layout.BlockLayoutCell("Cell1", {
content: [
new sap.m.Text("sample", {text: "test"})
]
})
]
})
]
})
]
});
var viewID = this.getView().sId;
viewID = viewID + "--detailPage-cont";
oLayout.placeAt(viewID);
When I check debugger if some content were added I see added content without cells and text.
hope this can help
https://jsbin.com/benogay/edit?html,js,output
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-libs="sap.m, sap.ui.table" data-sap-ui-theme="sap_bluecrystal">
</script>
<script>
sap.ui.define([
'sap/ui/core/mvc/Controller',
'sap/ui/layout/VerticalLayout',
'sap/ui/layout/BlockLayout',
'sap/ui/layout/BlockLayoutRow',
'sap/ui/layout/BlockLayoutCell',
'sap/m/Text'
], function(Controller, VerticalLayout, BlockLayout, BlockLayoutRow, BlockLayoutCell, Text) {
sap.ui.jsview("myView.Template", {
getControllerName: function() {
return "myView.Template";
},
createContent: function(oController) {
return new VerticalLayout({
content: new BlockLayout({
content: new BlockLayoutRow({
content: new BlockLayoutCell({
content: new Text({
text: "test"
})
})
})
})
});
}
});
Controller.extend("myView.Template", {
onInit: function(oEvent) {
},
});
});
var view = sap.ui.view({
type: sap.ui.core.mvc.ViewType.JS,
viewName: "myView.Template"
});
view.placeAt("content");
</script>
</head>
<body class="sapUiBody sapUiSizeCompact" role="application">
<div id="content"></div>
</body>
</html>

highchart cannot addSeries

Using HighChart, I am trying to add a data series, but it doesn't seem to work.
I am getting an error.
"Uncaught TypeError: Cannot call method 'addSeries' of undefined"
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'target_div'
},
series: [{
name: 'Existing',
data: [0,0,0]
}]
});
});
chart.addSeries(
{
name: 'Test',
data: [1,2,3]
}
)
</script>
</head>
<body>
<div id='target_div'>
</body>
</html>
Is there something obvious that I am missing?
This worked!
$(chart).ready(function() {
chart.addSeries(
{
name: 'test',
data: [1,2,3]
}
)
});
You have to add chart.addSeries inside $(document).ready.
When it's getting executed chart isn't an instance of Highcharts.
Demo

Categories

Resources