Pass Dynamic value from backend to jQplot piechart? - javascript

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.

Related

My select element doesn't get populated with model data

I'm writing a small OpenUI5 application. I would like to attach a model (list with key/text values) to a sap.m.Select element (drop-down box).
However, regardless of whether I use static data for the model or fetch the data through ajax, the select element remains empty, no drop-down is displayed. I thought I had followed the examples/tutorials but I can't see what the problem is.
index.html:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Q Ui5 POC</title>
<script id="sap-ui-bootstrap" src="resources/sap-ui-core.js"
data-sap-ui-theme="sap_belize"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-async="true"
data-sap-ui-onInit="module:de/xx/qpoc/index"
data-sap-ui-resourceroots='{ "de.xx.qpoc": "./" }'
></script>
</head>
<body id="content" class="sapUiBody"></body>
</html>
index.js:
sap.ui.define([
"sap/ui/core/mvc/XMLView",
], function (XMLView) {
"use strict";
XMLView.create({
id: "qpocMainView",
viewName: "de.xx.qpoc.view.App",
}).then(function(oView) {
oView.placeAt("content");
});
});
App.view.xml:
<mvc:View controllerName="de.xx.qpoc.controller.App"
xmlns="sap.m"
xmlns:layout="sap.ui.layout"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
displayBlock="true">
<layout:VerticalLayout>
<Select
enabled="true"
editable="false"
forceSelection="false"
items="{
path: '/clientList',
sorter: { path: 'text' }
}">
<core:Item key="{key}" text="{text}" />
</Select>
</layout:VerticalLayout>
</mvc:View>
App.controller.js:
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
], function (Controller, JSONModel) {
"use strict";
return Controller.extend("de.xx.qpoc.controller.App", {
onInit: function() {
var viewData = {
"clientList": [
{ key: 'key1', text: 'text1'},
{ key: 'key2', text: 'text2'},
]
};
var oModel = new JSONModel(viewData);
this.getView ().setModel(oModel);
}
});
});
I have removed all non-relevant UI elements and application logic. My understanding is that I do the binding in the onInit method of the controller. And that I can reference keys of the JSON structure I'm passing to the JSONModel constructor in the UI element (/clientList).
The generated UI looks like this:
Remove those two lines in your XML view or set them to true (default value):
editable="false" → makes the control non-interactive
forceSelection="false" → none of the options will be selected preliminarily
You do have data bound. It's just the settings that prevented them from displaying.

tags input with typeahead from server local data source

I want to synthesize a Json array of objects for the auto complete from server side, and for now I hard coded something like below when page loads but it didn't work. However when I changed it like "local: [{ name: 'Foo' }, { name: 'FFoo' }, { name: 'Ah' }]" in JS file, it works.
Is it possible to render the "local" data from server side and how can I make a Json string using Vb.net?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
hdTypeahead.Value = "[ { 'name': 'ah'},{ 'name': 'ba'},{ 'name': 'cha'} ]"
End Sub
var dataSetBloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
//local: $('#<%= hdTypeahead.ClientID %>').val()
local: [{ name: 'Foo' }, { name: 'FFoo' }, { name: 'Ah' }]
});
dataSetBloodhound.initialize();
$('input').tagsinput({
freeInput: true,
typeaheadjs: {
name: 'dataSetBloodhound',
displayKey: 'name',
valueKey: 'name',
source: dataSetBloodhound.ttAdapter()
}
});
<link href="https://rawgit.com/timschlechter/bootstrap-tagsinput/master/src/bootstrap-tagsinput.css" rel="stylesheet"/>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<script src="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js"></script>
<input type="text" value="Amsterdam,Washington,Sydney,Beijing,Cairo" data-role="tagsinput" />
<input runat="server" id="hdTypeahead" type="text" value="" style="display:none"/>
try
local: JSON.parse($('#<%= hdTypeahead.ClientID %>').val())
or please open console log to the same page and get exact value of this element from $('#<%= hdTypeahead.ClientID %>')
The problem is not with your data coming from server side it is actually parsing of java script array to a variable. Your data is stored in string format in hdTypeahead control's val, so in order to make it an array you have to use some parser present in java script. I have implemented the code as follows:
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input id="hidTypeAhead" type="hidden" runat="server" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var typeAhead = JSON.parse($('#<%= hidTypeAhead.ClientID %>').val());
console.log(typeAhead.data);
</script>
</body>
</html>
WebForm1.aspx.vb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tempApp2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
hidTypeAhead.Value = #"{""data"":[{ ""name"": ""Foo"" }, { ""name"": ""FFoo"" }, { ""name"": ""Ah"" }]}";
}
}
}
So first understand that you have array data in string not some object while JS have JSON.parse() method which can parse string to JS object. So you simply have to add your array to an object within the string as I have done as follows:
hidTypeAhead.Value = #"{""data"":[{ ""name"": ""Foo"" }, { ""name"": ""FFoo"" }, { ""name"": ""Ah"" }]}";
I have added my array in data property of the JS object. The next part is to parse it using JSON.parse() the following code will do the needy:
var typeAhead = JSON.parse($('#<%= hidTypeAhead.ClientID %>').val());
So that's it you will get your array in typeAhead variable's "data" property which you can then assign to your property "local" as
local: typeAhead.data
Or directly
local: JSON.parse($('#<%= hidTypeAhead.ClientID %>').val()).data;
Hope it helps

Can we get data in aspx.cs page from Angular controller?

I have a project which contains all plain html pages with angularJS and one .aspx page. I need some data in list/json format in my aspx page's code behind from angular controller. Can this be done ? If yes, please guide.
I'm new to angular, please be kind.
Scenario is I want to download the current html page as pdf. I found jspdf but for some reason it is not working in IE, works in chrome.
So, I am putting a workaround where I can do this with aspx page, I just need data there.
//Download PDF
$scope.PDFDownload = function () {
window.open('ReportPage.aspx');
//need to send list/json data to aspx code behind here.
}
I need some data in list/json format in my aspx page's code behind
from angular controller.
If you want to send/receive data to/from ASPX Web Form, you want to use WebMethod.
using System.Web.Script.Serialization;
namespace DemoWebForm
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostJson(string firstName, string lastName)
{
return new JavaScriptSerializer().Serialize(
"Hello, " + lastName + ", " + firstName + "!");
}
}
}
Usage
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body ng-app="demoApp">
<form id="form1" runat="server" ng-controller="DemoController">
<pre>{{user}}</pre>
<button type="button" onclick="ajaxPostData();">Post Data Ajax</button>
<button type="button" ng-click="ngPostData()">Post Data Angular</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function ajaxPostData() {
var user = { firstName: "John", lastName: "Doe" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
data: JSON.stringify(user),
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
var demoApp = angular.module('demoApp', [])
.controller('DemoController', function DemoController($scope, $http) {
$scope.user = { "firstName": "John", "lastName": "Doe" };
$scope.ngPostData = function () {
$http.post('<%= ResolveUrl("~/default.aspx/postjson") %>', $scope.user)
.then(function (result) {
console.log(result.data.d);
});
}
});
</script>
</form>
</body>
</html>
Screen shot

MVC controller return JSON list

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,

Verb not displaying from xAPI statement

when I send this sample statement the verb is not displaying when I view the information in the LRS. The actor and other information is displaying correctly. Can someone tell me what I might be doing wrong? Thank you.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Statement</title>
<script src="js/tincan.js" type="text/javascript"></script>
<script type="text/javascript">
function init()
{
var tincan = new TinCan (
{
recordStores: [
{
endpoint: "https://lrs.adlnet.gov/xapi/",
username: "xapi-tools",
password: "xapi-tools",
allowFail: false
}
]
}
);
tincan.sendStatement(
{
actor: {
mbox: "mailto:myemailaddress#example.com"
},
verb: {
id: "http://adlnet.gov/expapi/verbs/attempted"
},
target: {
id: "http://tincanapi.com/activities/sending-my-first-statement"
}
},
function (err, result) {
//Handle any errors here. This code just outputs the result to the page.
document.write("<pre>");
document.write(JSON.stringify(err, null, 4));
document.write("</pre>");
document.write("<pre>");
document.write(JSON.stringify(result, null, 4));
document.write("</pre>");
}
);
}
</script>
</head>
<body onload='init()'>
Most likely nothing. Your statement could be "improved" by supplying a 'display' property and including one or more language code/value pairs inside of it so that the statement includes a "human readable" version of that object. I would think TinCanJS would have been doing that for you for that verb.

Categories