I can't seem to get morris.js graph working in rails, using coffeescript. It does not even appear to be rendering on the page. I have managed to get the tutorial graph rendering, which makes me believe it is an issue with my controller (and that my gem files etc are loaded correctly), but I'm totally lost. My console output is below:
Coffeescript
jQuery ->
$.get '/scores/index.json', (data) ->
Morris.Line
element: $('#myfirstchart')
data: data
xkey: 'created_at'
ykeys: ['scores']
labels: ['Score']
index.html.erb
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<div id="myfirstchart" style="border:2px solid red; height: 200px; width: 100%"></div>
scores_controller.rb
def index
respond_to do |format|
format.html {
# Display current users scores in the order of created at descending from most recent. Taking the last 5 scores
#scores = Score.all
}
format.json {
scores = Score.all
render :json => scores
}
end
end
Any help would be hugely appreciated.
According to the docs, the <script> tag should be inside the <head> section. In your application.html.erb:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<!-- other Rails imports -->
</head>
<body>
<%= yield %>
</body>
</html>
See jQuery Get Started for an example.
I had this issue. The fix was to put the records I wanted into a helper and then call that in the JS to render in the view. Get your helper to show the data in the way Morris requires then you’ll be good.
Inside of a helper:
def chart_data
(1.month.ago.to_date..Date.today).map do |date|
{
period: date,
score: Score.where("date(created_at) = ?", date).count,
}
end
end
In your view:
<%= content_tag :div, "", style: "height: 205px", id: "scores-morris", data: {scores: chart_data} %>
And finally add your js/coffee script. This is coffee:
$ ->
Morris.Line
element: 'scores-morris'
data: $('#scores-morris').data('scores')
xkey: 'period'
ykeys: [ 'score' ]
labels: [ 'SCORE!!!' ]
hideHover: [ 'auto' ]
Related
I am trying to make a chatbot from Cognigy.ai. I made a small bot but I am not able to customize it's webchat interface from the Github repo, but I am not able to figure out how to do it?
This is the endpoint of my chatbot:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
html {
background-color: #eee;
}
</style>
</head>
<body>
<!-- 1. Load the webchat.js bundle via a script tag -->
<script src="https://github.com/Cognigy/WebchatWidget/releases/download/v2.20.0/webchat.js"></script>
<!-- Initialize the Webchat towards a Cogngiy Endpoint via initWebchat() -->
<script>
initWebchat(
"https://endpoint-trial.cognigy.ai/8a8b023c1da283e1c9191c471aaef8dc5090ccc8f33d6a39b00a80276754309e",
{
userId: "documentation-reader",
forceWebsockets: true
}
);
</script>
</body>
</html>
I am trying to remove the 'Powered by Cognigy AI' line from the webchat interface. In the Github repo they mentioned that I need to disableBranding = True. But where should I write it?
The Github repo for customization is:
https://github.com/Cognigy/WebchatWidget/blob/master/docs/embedding.md
Like this,
<script>
initWebchat(
"https://endpoint-trial.cognigy.ai/8a8b023c1da283e1c9191c471aaef8dc5090ccc8f33d6a39b00a80276754309e",
{
settings: {
colorScheme: "#fab",
disableBranding: true
}
}
);
</script>
You need to add
settings: {
disableBranding: true
}
after the line:
forceWebsockets: true,
make sure you add a comma after forceWebsockets: true = forceWebsockets: true,
As it is mentioned in their documentation:
Name: Settings | Type: Endpoint Settings
I'm trying to return a JSON list in my controller. Not sure where I am going wrong. Any help would be greatly appreciated. I am trying to implement a grid a found online.
Here is my controller:
//[HttpPost]
public JsonResult JqueryTest()
{
var estimateDetails = db.EstimateDetail
.Include(x => x.EstimationItem)
.Include(x => x.EstimateHeader);
return Json(estimateDetails, JsonRequestBehavior.AllowGet);
}
Here is my view:
#model IEnumerable < EstimationTools.Models.Entities.EstimateDetail >
ViewBag.Title = "JqueryTest";
}
<h2>JqueryTest</h2>
<html lang="en">
<head>
<!-- The jQuery library is a prerequisite for all jqSuite products -->
<script type="text/ecmascript" src="../../../js/jquery.min.js"></script>
<!-- We support more than 40 localizations -->
<script type="text/ecmascript" src="../../../js/trirand/i18n/grid.locale-en.js"></script>
<!-- This is the Javascript file of jqGrid -->
<script type="text/ecmascript" src="../../../js/trirand/jquery.jqGrid.min.js"></script>
<!-- This is the localization file of the grid controlling messages, labels, etc.
<!-- A link to a jQuery UI ThemeRoller theme, more than 22 built-in and many more custom -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- The link to the CSS that the grid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="../../../css/trirand/ui.jqgrid-bootstrap.css" />
<script>
$.jgrid.defaults.width = 780;
$.jgrid.defaults.styleUI = 'Bootstrap';
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<meta charset="utf-8" />
<title>jqGrid Loading Data - JSON</title>
</head>
<body>
<div style="margin-left:20px">
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'EstimationTool/plugins/jqGrid',
datatype: "json",
colModel: [
{ label: 'Estimate', name: 'Estimate', width: 75 },
{ label: 'Contingency', name: 'Contingency', width: 90 },
{ label: 'Comment', name: 'Comment', width: 100 },
{ label: 'Subactivity', name: 'EstimationItem.Subactivity', width: 100 },
{ label: 'EstimationArea', name: 'EstimationItem.Area.EstimationArea', width: 100 },
{ label: 'Description', name: 'EstimationItem.GeneralActivity.Description', width: 100 }
// sorttype is used only if the data is loaded locally or loadonce is set to true
],
viewrecords: true, // show the current page, data rang and total records on the toolbar
width: 780,
height: 200,
rowNum: 30,
loadonce: true, // this is just for the demo
pager: "#jqGridPager"
});
});
</script>
</body>
</html>
First thing first... as stephen.vakil states, there is an error in your url, as you are pointing to an action so called "jqGrid":
url: 'EstimationTool/plugins/jqGrid'
The usual syntax is: '{Controller}/{Action}/'
Which in your case, the action name is "JqueryTest" as stated above. So, I don't know the name of your Controller, but I hope you've got the idea. Something like this:
url: 'YourController/JqueryTest'
On the other hand, within your Action, you should return a list instead... so, just add .ToList() at the end of the query or append it to your parameter:
return Json(estimateDetails.**ToList()**, JsonRequestBehavior.AllowGet);
Regards,
I am displaying line chart using easy dashboard java script library.But it is throwing error
401 login required.I created project in Google developer console and generated keys for it.
As 401 error code explains that credentials are wrong.Tell me what is the fault.
Any help will be appreciated.Thanks in advance
Here is the code for this
<!DOCTYPE>
<html>
<head><title>GA Dash Demo</title></head>
<body>
<!-- Add Google Analytics authorization button -->
<button id="authorize-button" style="visibility: hidden">
Authorize Analytics</button>
<!-- Div element where the Line Chart will be placed -->
<div id='line-chart-example'></div>
<!-- Load all Google JS libraries -->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script src="gadash-1.0.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=gadashInit" type="text/javascript"></script>
<script type="text/javascript">
// Configure these parameters before you start.
var API_KEY = 'AIzaSyA2LNhLKC4yvO9CmYXhp3tKjEvtd9GGZbc';
var CLIENT_ID = '1096873113711-c8j9vt2ilnh6gbb0rshhfk3j89qv9pb5.apps.googleusercontent.com';
var TABLE_ID = 'ga:91837123';
// Format of table ID is ga:xxx where xxx is the profile ID.
gadash.configKeys({
'apiKey': API_KEY,
'clientId': CLIENT_ID
});
// Create a new Chart that queries visitors for the last 30 days and plots
// visualizes in a line chart.
var chart1 = new gadash.Chart({
'type': 'LineChart',
'divContainer': 'line-chart-example',
'last-n-days': 30,
'query': {
'ids': TABLE_ID,
'metrics': 'ga:visitors',
'dimensions': 'ga:date'
},
'chartOptions': {
height: 600,
title: 'Visits in January 2011',
hAxis: { title: 'Date' },
vAxis: { title: 'Visits' },
curveType: 'function'
}
}).render();
</script>
</body>
</html>
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.
I am using jQplot and JavaScript. I want to generate piechart from backing bean values in jQplot instead of static array.
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<a4j:loadStyle src="../../resources/chart/css/jquery.jqplot.css"/>
<a4j:loadScript src="../../resources/chart/jqplot-javascript/jquery-1.3.2.min.js"/>
<a4j:loadScript src="../../resources/chart/jqplot-javascript/jquery.jqplot.min.js"/>
<a4j:loadScript src="../../resources/chart/jqplot-javascript/jqplot.pieRenderer.min.js"/>
<script type="text/javascript">
var jsonPieObj = {
"pageHits": [
['JAN 2009', 120],
['Feb 2009',60],
['Mar 2009',22],
['Apr 2009',5],
['May 2009',60],
['June 2009',30],
['Jul 2009',22]]
};
$(function() {
$('#pieChartButton1').click(function() {
$('#chartDiv').html('');
$.jqplot('chartDiv', [jsonPieObj.pageHits], CreatePieChartOptions1());
});
});
function CreatePieChartOptions1()
{
var optionsObj = {
title: 'Blog Statistics',
legend: {
show: true,
location: 'nw'
},
seriesDefaults:{
shadow: true,
renderer:$.jqplot.PieRenderer,
rendererOptions:{
sliceMargin:10,
shadowOffset:1,
shadowAlpha:0.5,
shadowDepth:5
}
},
highlighter: {
showTooltip: true,
tooltipFade: true
}
};
return optionsObj;
}
</script>
</head>
<body>
<h:form id="pieChartForm">
<rich:panel id="pieChartRichPanel">
<div>
<rich:panel>
<div id="chartDiv" style="width:600px; height:400px;" />
</rich:panel>
</div>
<div>
<input id="pieChartButton1" type="button" value="Pie Chart for Page Hits" />
</div>
</rich:panel>
</h:form>
</body>
</html>
</f:view>
My static content :
var jsonPieObj = {
"pageHits": [
['JAN 2009', 120],
['Feb 2009',60],
['Mar 2009',22],
['Apr 2009',5],
['May 2009',60],
['June 2009',30],
['Jul 2009',22]]
};
Help me about this.
Thanks in advance.
Create a model object representing a page hit.
public class PageHit {
private String period;
private Integer hits;
// Add/generate the usual c'tor/getter/setter boilerplate.
}
Populate it in your bean somehow as a List<PageHit>.
public class Bean {
private List<PageHit> pageHits;
public Bean() {
pageHits = loadItSomehow();
}
// Add/generate getters, etc.
}
Import JSTL core in your JSP (put jstl-1.2.jar in /WEB-INF/lib for the case you don't have it yet):
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Use JSTL <c:forEach> tag to iterate over List<PageHit> and print it as if it's a JS array:
var jsonPieObj = {
"pageHits": [
<c:forEach items="#{bean.pageHits}" var="pageHit" varStatus="loop">
['${pageHit.period}', ${pageHit.hits}]${!loop.last ? ',' : ''}
</c:forEach>
]};
That's it.
Open page in webbrowser, rightclick and choose View Source to check if it has done its job properly. I.e., the generated JS code has no syntax errors.