Creating an Angular Chart using AJAX [duplicate] - javascript

This question already has an answer here:
updating high chart on real time in angular js after a particular time
(1 answer)
Closed 5 years ago.
I'm using angular-chart.js to create a chart using the example code below. This works but I'd like to create a chart dynamically using AJAX. If I insert the chart using AJAX the chart does not load. I would like to know how I can change the below code to allow me to dynamically create an Angular Chart using AJAX?
Example HTML file
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.css"></link>
</head>
<body>
<!-- If I try to insert the below using AJAX the chart does not load -->
<div ng-app="app">
<div ng-controller="ChartController as vm">
<canvas id="bar" class="chart chart-bar" chart-data="vm.barChart.data" chart-labels="vm.barChart.labels"></canvas>
</div>
</div>
<script>
angular
.module('app', ['chart.js'])
.controller('ChartController', ChartController);
function ChartController() {
var vm = this;
// Data
vm.barChart = {
labels: ['2006', '2007', '2008', '2009', '2010', '2011', '2012'],
series: ['Series A', 'Series B'],
data: [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
]
};
}
</script>
</body>
</html>
Update: My question is marked as duplicate but I'm sure this is different as I'm asking how to 'create' not 'update' a chart after the DOM has already been loaded. I think I should have been more clear, I'm not asking how to update the chart data using AJAX, I'm asking how to actually 'create' the chart using AJAX. I can only seem to create the chart when DOM loads for the first time, not after.

In AngularJS, you could to use Services.
AngularJS services are substitutable objects that are wired together
using dependency injection (DI). You can use services to organize and
share code across your app.
You can declare an AngularJS Service by this way:
.service("MyService", ["$http", function($http) {
return {
getMyData: function() { // This service method can be called from the controller.
return $http.get("https://gist.githubusercontent.com/dannyjhonston/4fade791505e812eae1a3fea2cde6ac4/raw/d73d8eb12cff8911b6b7c681718a760129ae1299/angular-chart-data.json", null, {
responseType: "json"
});
}
};
}])
Where:
"MyService": Service name. You can inject this service through this name to the AngularJS Controller.
"$http": $http: A core AngularJS service that facilitates communication with the remote HTTP servers via the browser's
XMLHttpRequest object or via JSONP. The $http service is a
function which takes a single argument that is used to generate an
HTTP request and returns a promise.
Inject the AngujarJS Service in the AngularJS Controller:
.controller("ChartController", ["MyService", ChartController]);
To call the AngularJS Service method from the AngularJS Controller and handle the received data, you could use this:
MyService.getMyData().then(function(response) {
// Data.
vm.barChart = response.data;
}, function(response) {
console.log("Error: " + response);
});
AJAX requires an URL that could return a JSON object, in this case.
URL: https://gist.githubusercontent.com/dannyjhonston/4fade791505e812eae1a3fea2cde6ac4/raw/d73d8eb12cff8911b6b7c681718a760129ae1299/angular-chart-data.json
JSON:
{
"labels": ["2006", "2007", "2008", "2009", "2010", "2011", "2012"],
"series": ["Series A", "Series B"],
"data": [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
]
}
See this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.css">
</head>
<body>
<div ng-app="app">
<div ng-controller="ChartController as vm">
<canvas id="bar" class="chart chart-bar" chart-data="vm.barChart.data" chart-labels="vm.barChart.labels"></canvas>
</div>
</div>
<script>
angular
.module("app", ["chart.js"])
.service("MyService", ["$http", function($http) {
return {
getMyData: function() {
return $http.get("https://gist.githubusercontent.com/dannyjhonston/4fade791505e812eae1a3fea2cde6ac4/raw/d73d8eb12cff8911b6b7c681718a760129ae1299/angular-chart-data.json", null, {
responseType: "json"
});
}
};
}])
.controller("ChartController", ["MyService", ChartController]);
function ChartController(MyService) {
var vm = this;
MyService.getMyData().then(function(response) {
// Data.
vm.barChart = response.data;
}, function(response) {
console.log("Error: " + response);
});
}
</script>
</body>
</html>
Hope this helps.

Here is a way to get chart data dynamically via ajax.
Key is to set the data property of your chart via another function.
To get data via ajax it makes sense to put this functionality into it's own service and link this service to the controller.
the getData() function of the service can be triggered anytime by buttons or periodically via timers ($timeout)
In this example I used an external file called data.json with the following content:
[
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
]
Happy coding!
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.css"></link>
</head>
<body>
<!-- If I try to insert the below using AJAX the chart does not load -->
<div ng-app="app">
<div ng-controller="ChartController as vm">
<canvas id="bar" class="chart chart-bar" chart-data="vm.barChart.data" chart-labels="vm.barChart.labels"></canvas>
</div>
</div>
<script>
angular
.module('app', ['chart.js'])
.service('ChartService', ['$http', ChartService])
.controller('ChartController', ['ChartService', ChartController]);
function ChartService($http) {
this.getData = function (callback) {
$http.get('data.json').success(function(response) {
console.log("Got data: " + response);
if (callback) callback(response);
});
};
}
function ChartController(chartService) {
var vm = this;
// Data
vm.barChart = {
labels: ['2006', '2007', '2008', '2009', '2010', '2011', '2012'],
series: ['Series A', 'Series B'],
data: []
};
function callback(data) {
vm.barChart.data = data;
}
chartService.getData(callback);
}
</script>
</body>
</html>

Related

set Theme using plugin in Chartjs 3.9.1

I'm trying to set theme using plugin in New version of chartjs 3.9.1, i'm trying to add "chartjs-plugin-colorschemes" plugin, link is: https://nagix.github.io/chartjs-plugin-colorschemes/.
In old version of chartjs v2.9.3 is working fine with this plugin.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="chartMenu">
<p>WWW.CHARTJS3.COM (Chart JS 3.9.1)</p>
</div>
<div class="chartCard">
<div class="chartBox" style="width: 500px">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-colorschemes/0.4.0/chartjs-plugin-colorschemes.min.js">
</script>
<script>
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [1, 2, 3].map(function (i) {
return {
label: 'Dataset ' + i,
data: [0, 0, 0, 0, 0, 0, 0].map(Math.random),
fill: false
}
})
};
const config = {
type: 'line',
data,
options: {
plugins: [
{
"colorschemes": {
scheme: 'brewer.RdYlBu3',
}
}]
},
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
</body>
</html>
Here is the code that I tried, can someone please guide me what i missed.
thanks.
It was never correctly updated for V3 so the only thing you can try is if the export they do also works for CDN version of distribution and try to register it. Otherwise you will need to wait until or if the plugin ever gets updated to work with V3 and above:
This might work if CDN version supports it, otherwise you are out of luck and need to stay with V2 or implement the plugin and coloring yourself:
Chart.register(ColorSchemesPlugin);
const data = {};
const config = {};
new Chart(ctx, config);
The demo site uses chart.js v2.8.0. As you can see on this page, the plugin you try to use doesn't work for chart.js v3 and later.
You probably can take a look at this pluging and adapt it to your need to generate the colors you want to use.
Here is some work around,
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Chart JS with www.chartjs3.com</title>
</head>
<body>
<div class="chartMenu">
<p>WWW.CHARTJS3.COM (Chart JS 3.9.1)</p>
</div>
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"
integrity="sha512-UXumZrZNiOwnTcZSHLOfcTs0aos2MzBWHXOHOuB0J/R44QB0dwY5JgfbvljXcklVf65Gc4El6RjZ+lnwd2az2g=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/1.2.1/chartjs-plugin-zoom.min.js"
integrity="sha512-klQv6lz2YR+MecyFYMFRuU2eAl8IPRo6zHnsc9n142TJuJHS8CG0ix4Oq9na9ceeg1u5EkBfZsFcV3U7J51iew=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
const dt = [];
const labels = [];
for (let index = 1; index < 20; index++) {
labels.push("Label_" + index);
dt.push(index);
}
var ThemeDictionary = {
Classic10: ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"],
ClassicMedium10: ["#729ece", "#ff9e4a", "#67bf5c", "#ed665d", "#ad8bc9", "#a8786e", "#ed97ca", "#a2a2a2", "#cdcc5d", "#6dccda"],
ClassicLight10: ["#aec7e8", "#ffbb78", "#98df8a", "#ff9896", "#c5b0d5", "#c49c94", "#f7b6d2", "#c7c7c7", "#dbdb8d", "#9edae5"],
Classic20: ["#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5"],
ClassicGray5: ["#60636a", "#a5acaf", "#414451", "#8f8782", "#cfcfcf"],
ClassicColorBlind10: ["#006ba4", "#ff800e", "#ababab", "#595959", "#5f9ed1", "#c85200", "#898989", "#a2c8ec", "#ffbc79", "#cfcfcf"],
ClassicTrafficLight9: ["#b10318", "#dba13a", "#309343", "#d82526", "#ffc156", "#69b764", "#f26c64", "#ffdd71", "#9fcd99"],
ClassicPurpleGray6: ["#7b66d2", "#dc5fbd", "#94917b", "#995688", "#d098ee", "#d7d5c5"],
ClassicPurpleGray12: ["#7b66d2", "#a699e8", "#dc5fbd", "#ffc0da", "#5f5a41", "#b4b19b", "#995688", "#d898ba", "#ab6ad5", "#d098ee", "#8b7c6e", "#dbd4c5"],
ClassicGreenOrange6: ["#32a251", "#ff7f0f", "#3cb7cc", "#ffd94a", "#39737c", "#b85a0d"],
ClassicGreenOrange12: ["#32a251", "#acd98d", "#ff7f0f", "#ffb977", "#3cb7cc", "#98d9e4", "#b85a0d", "#ffd94a", "#39737c", "#86b4a9", "#82853b", "#ccc94d"],
ClassicBlueRed6: ["#2c69b0", "#f02720", "#ac613c", "#6ba3d6", "#ea6b73", "#e9c39b"],
ClassicBlueRed12: ["#2c69b0", "#b5c8e2", "#f02720", "#ffb6b0", "#ac613c", "#e9c39b", "#6ba3d6", "#b5dffd", "#ac8763", "#ddc9b4", "#bd0a36", "#f4737a"],
ClassicCyclic13: ["#1f83b4", "#12a2a8", "#2ca030", "#78a641", "#bcbd22", "#ffbf50", "#ffaa0e", "#ff7f0e", "#d63a3a", "#c7519c", "#ba43b4", "#8a60b0", "#6f63bb"],
}
var Theme = "Classic10"
// setup
const data = {
labels: labels,
datasets: [{
label: 'Weekly Sales',
data: dt,
backgroundColor: ThemeDictionary[Theme],
borderWidth: 1
}]
};
// config
const config = {
type: 'bar',
data,
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true
}
}
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
</body>
</html>
You can create you own theme colors and add into "ThemeDictionary" dictionary with key and set your key into "Theme" variable, that's it.
Please suggest if anything I missed.

How to use the http.get method in angular to fetch the json data?

I created a funnel chart in java script . And converted into angular And now I'm trying to use the http.get method in angular to fetch the json data. And I'm stuck here and got confused in this part
And now let me show u my code part
---index.html---
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>FusionCharts - Funnel 3D Chart</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<script data-require="angular.js#1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.widgets.js"></script>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<script src="practice.js"></script>
</head>
<body ng-app="myApp">
<!-- A funnel 3D Chart showing a conversion analysis in percentage of visiting to purchase in Harry's Supermart website last year
Attribute :
# showPercentValues - set to 1 to show the values in percentage.
-->
<div id="chart-container" ng-controller="ParentCtrl" ng-init='load()' ng-model="dataSource1">FusionCharts will render here</div>
</body>
</html>
---script.js---
// Code goes here
//creating an application module
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http)
{
$scope.load = function(){
//alert("2");
FusionCharts.ready(function () {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource : "dataSource1"
});
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
$scope.dataSource1 = data1;// binding the data to the $scope variable
});
conversionChart.render();
});
};
});
----chart.json----
{
"chart": {
"caption": "Ensource sales report",
"subcaption": "Purchase - Conversion analysis for last year",
"decimals": "1",
"isHollow": "0",
"isSliced": "1",
"labelDistance": "15",
"plotTooltext": "Success : $percentOfPrevValue",
"theme": "fint",
"baseFontSize":"18"
},
"data":
[
{
"label": "Total",
"value": "385634"
},
{
"label": "Contacts",
"value": "175631"
},
{
"label": "Leads",
"value": "84564"
},
{
"label": "Sanctioned",
"value": "35654"
},
{
"label": "Disbursed",
"value": "12342"
}
]
}
Plunker:http:http://plnkr.co/edit/HUKvROQv8wIiFfx6uZBk?p=preview
Here i need to fetch the json data for dataSource :but not able to do that
All the script and css for the funnel chart is been included in index.html. My oly work is to fetch the json data using the http.get method.Plz help me with this
And thanks in advance ...
It seems you were just passing the incorrect param to the dataSource field. After some playing around with your plunker, instead of passing it a function where the $http call was executed, I passed it the data itself, as you can see below.
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http) {
$http.get('./chart.json') //reading the studentRecord.json file
.success(function(data1) {
$scope.dataSource = data1; // binding the data to the $scope variable
FusionCharts.ready(function() {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource: $scope.dataSource
});
conversionChart.render();
});
});
});
Notice I wrapped the code inside $http's success callback, so that we know that the data is present at the moment of rendering.
You can see the working plunker here.

get('url') operation using AngularJS and ServiceStack webservice

I am very new to AngularJS, and I am trying to get some items in JSON from a webservice I quickly made using ServiceStack. When I try the URL in the browser I can see the JSON object, but for some reason AngularJS fails to successfully get the data. Here's my implementation:
angular.module('SomeApp', []).controller('ItemsFetcher', [ '$http', function($http){
var x = this;
x.products= [
{
Name: 'Missing items',
Description: 'Could not access server'
}];
$http.get('http://localhost:29029/json/reply/GetAllItemsRequest')
.then(function(data){
x.products = [
{
Name: 'Success',
Description: 'Great stuff!'
}];
});
}]);
Here's the view:
<html ng-app="SomeApp">
<head>
<title>My First App</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="ItemsFetcher as fetcher">
<h3>PRODUCTS</h3>
<div ng-repeat="item in fetcher.products">
<div>{{item.Name}} - {{item.Description}}</div>
</div>
</body>
As I said, if I call http://localhost:29029/json/reply/GetAllItemsRequest in a browser, I can the JSON object.
Am I missing something ? Any ideas why this does not work ?
In case anyone could benefit from this, I had to either enable CORS (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) or to host both the webservice and website in the same place.

Load another page's HTML and parse it through selectors with jQuery

I tried as example on jsFiddle
$.get('/user/login/', function(content){ /* (jsFiddle.net/user/login is in the same domain) */
alert($('*',content).html());
});
But it returns
JSFiddle
What am I doing wrong? I'd like to fetch HTML's title for instance, but $('title',content) is not working
JSFiddle as far as I know won't allow AJAX calls.
EDIT: But they do offer some sort of simulation although I've not used it http://doc.jsfiddle.net/use/echo.html
Can do this without Ajax.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load remote content into object element</title>
</head>
<body>
<div id="siteloader"></div>​
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$("#siteloader").html('<object data="http://tired.com/">');
</script>
</body>
</html>
After getting the page try to parse it.
it will check jsfiddles login page. something like
http://jsfiddle.net/user/login/
you can use something like /echo/json/ as url:
<div class='wrapper'>
<p>JSON will be received in 3 seconds</p>
<ul id='post'></ul>
</div>
new Request.JSON({
url: '/echo/json/',
data: {
json: JSON.encode({
text: 'some text',
array: [1, 2, 'three'],
object: {
par1: 'another text',
par2: [3, 2, 'one'],
par3: {}
}
}),
delay: 3
},
onSuccess: function(response) {
show_response(response, $('post'));
}
}).send();
show_response = function(obj, result) {
$H(obj).each(function(v, k) {
new Element('li', {
text: k + ': ' + v
}).inject(result);
});
result.highlight();
};
jsfiddle demo:http://jsfiddle.net/zalun/QsHw4/#

Django template not executing js function

I have a django template that looks like this:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/jquery.flot.js"></script>
<!--<script src="c:/src/project/scraper/collegedata/templates/chart.js" type="text/javascript"></script>-->
<script src="{{ STATIC_URL }}js/chart.js" type="text/javascript"></script>
</head>
<body>
<div id="chart1" style="width:600px;height:300px"></div>
<script>
show_graph("{{ chart_type }}", {{ series_names }}, {{ data }}, {{ answer }});
</script>
<form action="start">
<input type="submit" value="Back to Questions" />
</form>
</body>
</html>
where show_graph is a function in chart.js. However, pycharm gives me one of two errors, either:
unresolved function or method show_graph(), or
invalid number of parameters passed: expected 4
and the function is clearly not being called.
I'm a little confused as to whether or not I can even pass template vars to a js function at all...
Does anyone have any insight?
EDIT:
this generates
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="/static/js/jquery.flot.js"></script>
<!--<script src="c:/src/project/scraper/collegedata/templates/chart.js" type="text/javascript"></script>-->
<script src="/static/js/chart.js" type="text/javascript"></script>
</head>
<body>
<div id="chart1" style="width: 600px; height: 300px;"></div>
<script>
show_graph("pie", [<ResponseOption: puddentane>, <ResponseOption: down the lane>], [1, 0], 0);
</script>
<form action="start">
<input value="Back to Questions" type="submit">
</form>
</body></html>
where chart.js looks like (values temporarily hardcoded for troubleshooting, and it should be mentioned that $.plot also gives an unresolved function error):
function show_graph(charttype, series_names, data, answer_index){
var data = [2000, 50, 400, 200, 5000];
var data3 = [
{ label: "my cat", data: 10, color: 'rgb(85, 96, 42)'},
{ label: "my friends", data: 20, color: 'rgb(105, 118, 52)'},
{ label: "my boyfriend", data: 30, color: 'rgb(125, 141, 62)'},
{ label: "my job", data: 30, color: '#42215F'},
{ label: "food", data: 10, color: 'rgb(145, 164, 72)'},
{ label: "social skills", data: 0, color: 'rgb(166, 189, 82)'}
];
alert("in chart.js");
var charttype = "pie";
var type = {};
type[charttype] = {show: true};
var chart_options = {};
chart_options["series"]=type;
var plot = $.plot($("#chart1"), data3, chart_options);
}
It looks like series_names is just being output as the HTML entities of an object without a proper __unicode__ method. You're getting:
show_graph("pie", [<ResponseOption: puddentane>,
Which, decoded, is:
show_graph("pie", [<ResponseOption: puddentane>, ...
What actually needs passing to the method? You probably need to think about how you want {{ series_names }} to be output, rather than just calling the string representation of that variable. What you're generating at the moment is invalid Javascript - the console of your browser will probably reinforce this point.
Invalid number of parameters means one of your context variables, probably answer, was blank.
Your code is risky because Django will escape your context variables to be HTML safe, not JavaScript safe. One trick I use to get around this is to put all the parameters to a JS function in a dictionary, then convert it to JSON and use that for the context variable (using it with the |safe filter, and the <![CDATA[ markup in the template if needed).
As for show_chart not being resolved, you might want to make sure chart.js really is being loaded, and that it's not in a namespace of some form.

Categories