highchart cannot addSeries - javascript

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

Related

Fill CanvasJS with json

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.

How to dynamically add points to a bar/pie chart in a Vue context?

I would like to bootstrap a Highcharts bar chart and later add some points to it (in a Vue container). The documentation mentions addPoint(), setData() and update() as means to achieve that, but none of the incantations I tried worked.
The demo for a post-updated pie chart makes it simple to use setData():
var chart = Highcharts.chart('container', {
chart: {
type: 'pie'
},
series: [{
data: []
}]
});
// the button action
$('#button').click(function() {
chart.series[0].setData([129.2, 144.0, 176.0]);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px"></div>
<button id="button" class="autocompare">Set new data</button>
I tried to replicate this in a Vue context but the chart is never updated
var chart = Highcharts.chart('container', {
chart: {
type: 'pie'
},
series: [{
data: []
}]
});
new Vue({
el: "#app",
data: {},
mounted() {
chart.series[0].setData([129.2, 144.0, 176.0]);
chart.redraw()
}
})
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div id="container" style="height: 400px"></div>
</div>
It appears that calling Highlights.chart queries the DOM immediately, so doing so before Vue's mounted callback is called will fail, since the element doesn't exist yet. That, or it gets overwritten by Vue's rendering. Instead, you'll want to call that function after Vue has mounted.
As a bonus, here's a little demo (that I had way too much fun with) which shows how the library can play along with Vue. It uses a watcher to redraw the chart when the corresponding property is changed.
function createChart() {
return Highcharts.chart('container', {
chart: {
type: 'pie'
},
series: [{
data: []
}]
})
}
new Vue({
el: "#app",
data: {
chartData: []
},
mounted() {
this.chart = createChart()
this.setData([100, 100, 100])
},
methods: {
setData(data){
this.chartData = data
}
},
watch: {
chartData(data) {
this.chart.series[0].setData(data)
this.chart.redraw()
}
}
})
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<button #click="setData([129.2, 144.0, 176.0])">Show First Dataset</button>
<button #click="setData([180, 100.0, 20.0])">Show Second Dataset</button>
<div id="container" style="height: 400px"></div>
</div>
You can use highcharts-vue, which is a wrapper on the highcharts library.
The following are the dependencies: "highcharts": "6.1.0",
"highcharts-vue": "1.0.4",
"vue": "^2.5.2"
Demo - https://codesandbox.io/s/highcharts-vue-demo-forked-ewn4n

Merging two json file and using it in autocoplete plugin

I am trying to merge two JSON file and using it in autocompleteplugin.
But I do get an error TypeError: $(...).easyAutocomplete is not a function even I have added js library for both auto complete and jquery.
My code look like this:
<script src="jquery-3.1.0.js"></script>
<link href="easy-autocomplete.min.css" rel="stylesheet" />
<script src="jquery.easy-autocomplete.min.js"></script>
<script>
$.getJSON("file1.json", function (data1) {
$.getJSON("file2.json", function (data2) {
var final = $.extend({}, data1, data2);
var options = {
data: final,
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
</script>
I made a working example based on your code.
Please check you have the correct paths when you include the script files. And also check if jQuery is included.
Hope will help you:
$.getJSON("https://api.myjson.com/bins/42jd0", function (data1) {
$.getJSON("https://api.myjson.com/bins/5bjqc", function (data2) {
var final = [];
final.push(data1.employees1);
final.push(data2.employees2);
var new_final = final[0].concat(final[1]);
var options = {
data: new_final,
getValue: "firstName",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/jquery.easy-autocomplete.min.js"></script>
<div class='easy-autocomplete'>
<input id="KUNDE"/>
</div>
You can run the code here by hitting the Run code snippet button or you can also check the jsfiddle I've made here.

Scope in Javascript callback

I expect to see the array ["foo", "bar"] at the second console.log(this.items). But instead, I get undefined.
Here is the jsBin.
How do I get ["foo", "bar"] instead of undefined?
http://jsbin.com/hodegimohu/edit?html,console,output
<!doctype html>
<head>
<meta charset="utf-8">
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<dom-module id="x-element">
<script>
(function(){
Polymer({
is: 'x-element',
properties: {
items: {
type: Array,
value: ['foo','bar']
},
},
ready: function(){
console.log(this.items) // ["foo", "bar"]
google.charts.load('current', {
'packages': ['geochart']
});
google.charts.setOnLoadCallback(this._drawRegionsMap);
},
_drawRegionsMap: function() {
console.log(this.items); // undefined
},
});
})();
</script>
</dom-module>
<x-element></x-element>
</body>
Just use .bind.
google.charts.setOnLoadCallback(this._drawRegionsMap.bind(this));
Nothing more than appropriately handling the callback (Nothing polymer based).

ASP.Net - Invalid Json String

I have been developing a web application in ASP.Net, which should return information from a database via a Web Service class.
From there, I wish to bind the data to a Google Combo chart.
The data can be bound to a grid view, so I know the method to call from the database is working, but when I try to bind it to the chart I receive the error message:
Invalid Json String:
!Doctype HTML
html lang = "en"
This is my first time working with javascript, so I assume that my javascript methods are accessing the wrong data, but I'm not sure where I'm going wrong.
If anybody could let me know what I have done wrong, it would be appreciated.
DEFAULT.ASPX
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var jsonData = $.ajax({
url: "Default.aspx/GetChartData",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Chart Title',
vAxis: { title: 'Scores %' },
hAxis: { title: 'Counties' },
seriesType: 'bars',
series: {
2: {
targetAxisIndex: 1
},
vAxes: {
1: {
title: '1',
textStle: { color: 'red' }
}
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<asp:GridView ID="Grid1D" runat="server"
AutoGenerateColumns = "true" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
PageSize = "10" Caption = "1-Dimensional Array">
</asp:GridView>
<div id ="chart_div" style="width:500px;height:400px"></div>
<asp:Literal ID="ltScripts" runat="server"></asp:Literal>
</body>
</html>
Sounds a lot like your call to Default.aspx/GetChartData returns an error page from the IIS that is hosting it. You should take a look at your jsonData variable, as it is anything but json.

Categories

Resources