Related
I'm receiving following JSON response from our servers and my requirement is to display the servlet details.
if(dataStoreLogFileSize > 10 && "dataStoreLogLevel": "production".)
I have written following Javacript code snippet to penetrate the JSON by those values But it is not working properly. Can anyone help me with this please.
{
"web-app": {
"servlet": [{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "ksm#pobox.com",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreLogFileSize": 10,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "production",
"maxUrlLength": 500
}
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true,
"dataStoreInitConns": 10,
"dataStoreLogFileSize": 5,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "test",
"maxUrlLength": 500
}
}
],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"
},
"taglib": {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
}
+********************************************************************************+
//Some code above
let foo = data.filter(object => (object.dataStoreLogLevel === 'production'
&& object => (object.dataStoreLogFileSize > '10');
console.log('Servlet Details Test' + foo);
//Code continues
You can use this code to get dataStoreLogFileSize greater than 1gb and production dataStoreLogLevel.
const jsoncode = {
"web-app": {
servlet: [
{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "ksm#pobox.com",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
templateProcessorClass: "org.cofax.WysiwygTemplate",
templateLoaderClass: "org.cofax.FilesTemplateLoader",
templatePath: "templates",
templateOverridePath: "",
defaultListTemplate: "listTemplate.htm",
defaultFileTemplate: "articleTemplate.htm",
useJSP: false,
jspListTemplate: "listTemplate.jsp",
jspFileTemplate: "articleTemplate.jsp",
searchEngineListTemplate: "forSearchEnginesList.htm",
searchEngineFileTemplate: "forSearchEngines.htm",
searchEngineRobotsDb: "WEB-INF/robots.db",
useDataStore: true,
dataStoreClass: "org.cofax.SqlDataStore",
redirectionClass: "org.cofax.SqlRedirection",
dataStoreName: "cofax",
dataStoreDriver: "com.microsoft.jdbc.sqlserver.SQLServerDriver",
dataStoreUrl:
"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
dataStoreUser: "sa",
dataStorePassword: "dataStoreTestQuery",
dataStoreTestQuery: "SET NOCOUNT ON;select test='test';",
dataStoreLogFile: "/usr/local/tomcat/logs/datastore.log",
dataStoreInitConns: 10,
dataStoreLogFileSize: "1GB",
dataStoreMaxConns: 100,
dataStoreConnUsageLimit: 100,
dataStoreLogLevel: "production",
maxUrlLength: 500
}
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
templatePath: "toolstemplates/",
log: 1,
logLocation: "/usr/local/tomcat/logs/CofaxTools.log",
logMaxSize: "",
dataLog: 1,
dataLogLocation: "/usr/local/tomcat/logs/dataLog.log",
dataLogMaxSize: "",
removePageCache: "/content/admin/remove?cache=pages&id=",
removeTemplateCache: "/content/admin/remove?cache=templates&id=",
fileTransferFolder:
"/usr/local/tomcat/webapps/content/fileTransferFolder",
lookInContext: 1,
adminGroupID: 4,
betaServer: true,
dataStoreInitConns: 10,
dataStoreLogFileSize: "0.5GB",
dataStoreMaxConns: 100,
dataStoreConnUsageLimit: 100,
dataStoreLogLevel: "test",
maxUrlLength: 500
}
}
],
"servlet-mapping": {
cofaxCDS: "/",
cofaxEmail: "/cofaxutil/aemail/*",
cofaxAdmin: "/admin/*",
fileServlet: "/static/*",
cofaxTools: "/tools/*"
},
taglib: {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
};
// jsoncode is your json response from server
const final = jsoncode['web-app'].servlet.filter((s) => {
// get the number from dataStoreLogFileSize
const size = s['init-param'].dataStoreLogFileSize.replace(/[^0-9\.]+/g, '');
// make sure the size is a number by adding a plus sign
return +size >= 1 && s['init-param'].dataStoreLogLevel === 'production';
});
console.log(final);
you're filtering the wrong array, the one having dataStoreLogLevel and dataStoreLogFileSize is in data['web-app'][0]['servlet']['init-param'], so you need to apply .filter on the data['web-app'].servlet array.
For the fileSize you'll need to use parseFloat to extract the size since it's a string.
You need to fix the .filter syntax.
and use , to console.log the result :
const data = {
"web-app": {
"servlet": [{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "ksm#pobox.com",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreLogFileSize": "1GB",
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "production",
"maxUrlLength": 500
}
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true,
"dataStoreInitConns": 10,
"dataStoreLogFileSize": "0.5GB",
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "test",
"maxUrlLength": 500
}
}
],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"
},
"taglib": {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
}
let foo = data['web-app'].servlet.filter(
object =>
object['init-param'].dataStoreLogLevel === 'production'
&& parseFloat(object['init-param'].dataStoreLogFileSize) >= 1 // change this to 10 for fileSize >= 10GB
);
console.log('Servlet Details Test', foo);
I'm trying to use savedQueries to draw graph without success. Is savedQueries only used to CRUD queries in Keen or can it actually be used to chart graph as well?? Keys removed from the code, sorry for the inconvenience.
var client = new Keen({
projectId: keen.project,
writeKey: keen.writeKey,
readKey: keen.readKey,
masterKey: keen.masterKey
});
var savedQueries = client.savedQueries();
savedQueries.get("monthly-active-users", function(err, response) {
if (err) {
console.log(err);
}
console.log(response);
var chart1 = new Keen.Dataviz()
.el(document.getElementById('chart'))
.chartType("area")
.colors(["#6ab975"])
.title("Monthly Active Users")
.prepare();
chart1
.data(response)
.render();
});
response obj from saved query
{
"refresh_rate": 0,
"user_last_modified_date": "2017-06-09T18:51:59.676000+00:00",
"last_modified_date": "2017-06-09T18:51:59.676000+00:00",
"query_name": "monthly-active-users",
"urls": {
"cached_query_url": "/3.0/projects/58f6fb8a90b3659264951b8d/queries/saved/monthly-active-users",
"cached_query_results_url": "/3.0/projects/58f6fb8a90b3659264951b8d/queries/saved/monthly-active-users/result"
},
"created_date": "2017-04-25T23:52:45.685000+00:00",
"query": {
"filters": [
{
"operator": "ne",
"property_name": "user_id",
"property_value": "guest"
},
{
"operator": "not_contains",
"property_name": "fromState",
"property_value": "app"
},
{
"operator": "not_contains",
"property_name": "user_email",
"property_value": "#giblib.com"
},
{
"operator": "not_contains",
"property_name": "fromState",
"property_value": "app.auth_postregister"
}
],
"analysis_type": "count_unique",
"timezone": "US/Pacific",
"group_by": null,
"force_exact": null,
"timeframe": "this_2_months",
"target_property": "user_id",
"interval": "monthly",
"event_collection": "user-page-access"
},
"run_information": null,
"metadata": {
"visualization": {
"chart_type": "areachart"
},
"display_name": "Monthly Active Users"
}
}
I noticed that you did not include the Keen.ready() function. Also, I recommend using client.run instead of client.get because it runs the query and gets the result.
I went ahead and created an example JSFiddle: https://jsfiddle.net/pn14bs0L/2/
Keen.ready(function() {
client.run("test-saved-query", function(err, response) {
if (err) {
// there was an error
} else {
var chart1 = new Keen.Dataviz()
.el(document.getElementById('my_chart'))
.chartType("areachart")
.colors(["#6ab975"])
.title("Monthly Active Users")
.prepare();
chart1
.data(response)
.render();
}
});
});
You can see this working with some test data in the JSFiddle.
Note: I assumed you were using keen-js here and not keen-dataviz.js.
You will get results on the fusioncharts website if you search up what I asked, but it is not exactly what I am looking for.
I am querying data from a MySQL database, and putting this data into a fusion chart to display on my webpage. I want there to be 2 graphs on the same page, and when you click on one of the datapoints on the parent graph, the child graph will display the "drilled down" graph. How can I do this? As of right now I can press on the parent graph and it will open the child graph on a new webpage. This is the code for the home page with the parent graph. The file is named "dept.php".
<?php
/*Include the `fusioncharts.php` file that contains functions
to embed the charts.
*/
include("includes/fusioncharts.php");
// Establish a connection to the database. Variables defined before
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
// Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
// Form the SQL query that returns the top 10 most populous countries
$strQuery = "SELECT Department, SUM(Quantity) AS Quantity FROM Scrap GROUP BY Department ORDER BY Department";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Sample Chart",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Department"],
"value" => $row["Quantity"],
"link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart. Initialize this object using the FusionCharts PHP class constructor. The constructor is used to initialize
the chart type, chart id, width, height, the div id of the chart container, the data format, and the data source. */
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
And then here is the other page that contains the child graph. The file is named "deptDrillDown.php".
<?php
/* Include the `includes/fusioncharts.php` file that contains functions to embed the charts.*/
include("includes/fusioncharts.php");
// Establish a connection to the database. Variables defined earlier
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
/*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
// Get the country code from the GET parameter
$countryCode = $_GET["Department"];
// Form the SQL query that returns the top 10 most populous cities in the selected country
$cityQuery = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = ? GROUP BY ScrapDate ORDER BY ScrapDate";
// Prepare the query statement
$cityPrepStmt = $dbhandle->prepare($cityQuery);
// If there is an error in the statement, exit with an error message
if($cityPrepStmt === false) {
exit("Error while preparing the query to fetch data from City Table. ".$dbhandle->error);
}
// Bind the parameters to the query prepared
$cityPrepStmt->bind_param("s", $countryCode);
// Execute the query
$cityPrepStmt->execute();
// Get the results from the query executed
$cityResult = $cityPrepStmt->get_result();
// If the query returns a valid response, prepare the JSON string
if ($cityResult) {
/* Form the SQL query that will return the country name based on the country code. The result of the above query contains only the country code.
The country name is needed to be rendered as a caption for the chart that shows the 10 most populous cities */
$countryNameQuery = "SELECT ScrapDate FROM Scrap WHERE Department = ?";
// Prepare the query statement
$countryPrepStmt = $dbhandle->prepare($countryNameQuery);
// If there is an error in the statement, exit with an error message
if($countryPrepStmt === false) {
exit("Error while preparing the query to fetch data from Country Table. ".$dbhandle->error);
}
// Bind the parameters to the query prepared
$countryPrepStmt->bind_param("s", $countryCode);
// Execute the query
$countryPrepStmt->execute();
// Bind the country name to the variable `$countryName`
$countryPrepStmt->bind_result($countryName);
// Fetch the result from prepared statement
$countryPrepStmt->fetch();
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Top 10 Most Populous Cities in ".$countryName,
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = $cityResult->fetch_array()) {
array_push($arrData["data"], array(
"label" => $row["ScrapDate"],
"value" => $row["Quantity"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is `FusionCharts("type of chart",
"unique chart id", "width of chart", "height of chart", "div id to render the chart", "data format", "data source")`.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
Back
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
n number of charts can be rendered in a single page using FusionCharts.
Store their chart references, e.g. in an associative array.
Use the dataplotClick event to capture the event being generated by clicking on a data.
Inside the callback, use the setJSONData to update the child chart, one wanna update.
A dummy code for this would be:
FusionCharts.ready(function () {
var chart1 = new FusionCharts({
type: 'msstackedcolumn2d',
renderAt: 'chart-container1',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: {
// enter the json data here
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
/* so every time a dataClickEvent is being triggered from the data plot,
a new json `json2` is fetched from a sql query and
chart2 is updated with it.*/
chart2.setJSONData(json2);
}
}
}
}).render();
});
Couple of days back I created this fiddle, hope this becomes useful here too. Instead of doing a SQL query, here we have a generalised data, every time a click is made, it internally makes a function call, and creates a data dynamically out of it. Lot of function calls for making it entirely dynamic might make the code look complex. But the basic philosophy I shared in the dummy code avobe is the same here.
The snippet version for the code for a quick reference.Better to run the result in full page to check whats exactly happening.
function getData() {
var arr = [{
seriesname: "Book A",
data: [{
"label": "Paper",
"value": 100
}, {
"label": "Promotion",
"value": 150
}, {
"label": "Transportation",
"value": 175
}, {
"label": "Royality",
"value": 200
}, {
"label": "Printing",
"value": 250
}, {
"label": "Binding",
"value": 275
}]
}, {
seriesname: "Book B",
data: [{
"label": "Paper",
"value": 130
}, {
"label": "Promotion",
"value": 110
}, {
"label": "Transportation",
"value": 155
}, {
"label": "Royality",
"value": 250
}, {
"label": "Printing",
"value": 210
}, {
"label": "Binding",
"value": 215
}]
}, {
seriesname: "Book C",
data: [{
"label": "Paper",
"value": 70
}, {
"label": "Promotion",
"value": 180
}, {
"label": "Transportation",
"value": 125
}, {
"label": "Royality",
"value": 150
}, {
"label": "Printing",
"value": 290
}, {
"label": "Binding",
"value": 245
}]
}, {
seriesname: "Book D",
data: [{
"label": "Paper",
"value": 150
}, {
"label": "Promotion",
"value": 100
}, {
"label": "Transportation",
"value": 105
}, {
"label": "Royality",
"value": 125
}, {
"label": "Printing",
"value": 278
}, {
"label": "Binding",
"value": 235
}]
}, {
seriesname: "Book E",
data: [{
"label": "Paper",
"value": 60
}, {
"label": "Promotion",
"value": 250
}, {
"label": "Transportation",
"value": 115
}, {
"label": "Royality",
"value": 189
}, {
"label": "Printing",
"value": 190
}, {
"label": "Binding",
"value": 285
}]
}, {
seriesname: "Book F",
data: [{
"label": "Paper",
"value": 190
}, {
"label": "Promotion",
"value": 200
}, {
"label": "Transportation",
"value": 160
}, {
"label": "Royality",
"value": 148
}, {
"label": "Printing",
"value": 178
}, {
"label": "Binding",
"value": 295
}]
}];
return arr;
}
function getValues(componentName) {
var i,
j,
arr = getData(),
valueArr = [],
len1;
for (i = 0, len = arr.length; i < len; i += 1) {
for (j = 0, len1 = arr[i].data.length; j < len1; j += 1) {
if (arr[i].data[j].label === componentName) {
valueArr.push({
value: arr[i].data[j].value
});
break;
}
}
}
return [{
seriesname: componentName,
data: valueArr
}];
}
function getProducts(componentName) {
var arr = getData(),
productArr = [];
for (i = 0, len = arr.length; i < len; i += 1) {
for (j = 0; j < arr[i].data.length; j += 1) {
if (arr[i].data[j].label === componentName) {
productArr.push({
"label": arr[i].seriesname,
"value": arr[i].data[j].value
});
break;
}
}
}
return productArr;
}
function getComponents(label, value) {
var arr = getData(),
sum,
i,
j,
len,
len1,
obj =
componentArr = [];
if (label === undefined) {
label = true;
}
if (value === undefined) {
value = true;
}
for (i = 0, len = arr[0].data.length; i < len; i += 1) {
sum = 0;
obj = {};
for (j = 0, len1 = arr.length; j < len1; j += 1) {
sum += arr[j].data[i].value;
}
if (label) {
obj.label = arr[0].data[i].label;
}
if (value) {
obj.value = sum;
}
componentArr.push(obj);
}
return componentArr;
}
function getSeriesNames() {
var arr = getData(),
seriesName = [];
for (i = 0, len = arr.length; i < len; i += 1) {
seriesName.push({
"label": arr[i].seriesname
});
}
return seriesName;
}
function getMode() {
var e = document.getElementById("interaction");
return e.options[e.selectedIndex].value;
}
FusionCharts.ready(function() {
var lastClickedId = true;
var pieChart = new FusionCharts({
type: 'pie2d',
renderAt: 'pieContainer',
width: '600',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Expenditures Incurred in Publishing a Book",
"subCaption": "Component-wise BreakUp",
"enableMultiSlicing": "0",
"bgcolor": "FFFFFF",
"showvalues": "1",
"showpercentvalues": "1",
"showborder": "0",
"showplotborder": "0",
"showlegend": "1",
"legendborder": "0",
"legendposition": "bottom",
"enablesmartlabels": "1",
"use3dlighting": "0",
"showshadow": "0",
"legendbgcolor": "#CCCCCC",
"legendbgalpha": "20",
"legendborderalpha": "0",
"legendshadow": "0",
"legendnumcolumns": "3",
"palettecolors": "#f8bd19,#e44a00,#008ee4,#33bdda,#6baa01,#583e78"
},
"data": getComponents()
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
if (getMode() === 'pie') {
var json = stackedChart.getJSONData(),
categoryLabel = dataObj.categoryLabel;
json.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
json.categories[0].category = getSeriesNames();
json.dataset = getValues(dataObj.categoryLabel);
stackedChart.setJSONData(json);
}
}
}
}).render();
var stackedChart = new FusionCharts({
type: 'stackedBar2D',
renderAt: 'barContainer',
width: '600',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"bgcolor": "FFFFFF",
"outcnvbasefontcolor": "666666",
"caption": "Expenditures Incurred in Publishing a Book",
"subCaption": "Product-wise BreakUp",
"xaxisname": "Expenditures Cost",
"yaxisname": "Cost",
"numberprefix": "$",
"showvalues": "0",
"numvdivlines": "10",
"showalternatevgridcolor": "1",
"alternatevgridcolor": "e1f5ff",
"divlinecolor": "e1f5ff",
"vdivlinecolor": "e1f5ff",
"basefontcolor": "666666",
"tooltipbgcolor": "F3F3F3",
"tooltipbordercolor": "666666",
"canvasbordercolor": "666666",
"canvasborderthickness": "1",
"showplotborder": "1",
"plotfillalpha": "80",
"showborder": "0",
"legendbgcolor": "#CCCCCC",
"legendbgalpha": "20",
"legendborderalpha": "0",
"legendshadow": "0",
"legendnumcolumns": "3"
},
"categories": [{
"category": getComponents(true, false)
}],
"dataset": getData()
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
if (getMode() === 'stackedBar') {
var JSON = pieChart.getJSONData(),
categoryLabel = dataObj.categoryLabel;
JSON.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
JSON.data = getProducts(categoryLabel);
pieChart.setJSONData(JSON);
pieChart.slicePlotItem(dataObj.datasetIndex);
}
}
}
}).render();
function resetFN() {
var json = pieChart.getJSONData();
json.chart.subCaption = "Component-wise BreakUp";
json.data = getComponents();
pieChart.setJSONData(json);
json = stackedChart.getJSONData();
json.chart.subCaption = "Product-wise BreakUp";
json.categories[0].category = getComponents(true, false);
json.dataset = getData();
stackedChart.setJSONData(json);
}
document.getElementById('reset').addEventListener('click', resetFN);
document.getElementById('interaction').addEventListener('change', resetFN);
});
h4 {
font-size: 20px;
margin-bottom: 10px
}
.intro {
margin: 0 auto;
background-color: #fff280;
padding: 15px
}
em {
font-style: italic
}
#interactionWrapper {
margin: 5px 10px;
}
button {
border: 1px solid #0b77bc;
background-color: #0d83ce;
color: #ffffff;
margin: 10px 0 0 15px;
padding: 5px 10px;
font-size: 14px;
cursor: pointer
}
.centerAlign {
text-align: center;
}
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<div class="intro">
<h4>Expenditures incurred while publishing books</h4>
<p><em>A company has 6 books to publish for this quater. The stacked chart shows component prices stacked as per different books. While the pie chart, shows the cumilative component price.</em></p>
<p>
<em>There are two interaction modes - namely "Interact in stacked chart" and "Interact in pie chart".On clicking in any plot on stacked chart, it shows the book-wise distribution of that component in the pie chart. Whereas on clicking the pie chart, for a component being clicked, it shows the book-wise distribution in the bar chart</em>
</p>
</div>
<div id="interactionWrapper">
<span>Interaction Mode:</span>
<span>
<select id="interaction">
<option value="stackedBar">Interact in stacked bar</option>
<option value="pie">Interact in the pie chart</option>
</select>
</span>
</div>
<div class="centerAlign">
<span id="barContainer">FusionCharts XT will load here!</span>
<span id="pieContainer">FusionCharts XT will load here!</span>
</div>
<button id="reset">Reset</button>
I have written a word cloud using vega.js to work for words with the frequency.
The wordset looks like this before appending to the spec:
[{"text":"really","value":40},{"text":"people","value":10}]
But when it appends to the spec it looks like this.
{
"name":"wordcloud",
"width":698.181818,
"height":198.181818,
"padding":{
"top":0,
"bottom":0,
"left":0,
"right":0
},
"data":[
{
"name":"table",
"values":"[{\"text\":\"really\",\"value\":40},{\"text\":\"people\",\"value\":10}]",
"transform":[
{
"type":"wordcloud",
"text":"data.text",
"font":"Helvetica Neue",
"fontSize":"data.value",
"rotate":{
"random":[-90,-45,0,45,90]
}
}
]
}
],
"marks":[
{
"type":"text",
"from":{
"data":"table"
},
"properties":{
"enter":{
"x":{
"field":"x"
},
"y":{
"field":"y"
},
"angle":{
"field":"angle"
},
"align":{
"value":"center"
},
"baseline":{
"value":"alphabetic"
},
"font":{
"field":"font"
},
"fontSize":{
"field":"fontSize"
},
"text":{
"field":"data.text"
}
},
"update":{
"fill":{
"value":"#f48fb1"
}
},
"hover":{
"fill":{
"value":"#f00"
}
}
}
}
]
}
Also the code gives two errors:
Uncaught TypeError: Cannot read property 'value' of undefined in line vega.js 4965
Uncaught TypeError: Cannot read property 'marktype' of undefined in line vega.js 9604
Can anyone help me to solve this problem?
The written javascript function for the word cloud.
var textData="";
function drawPersonWordCloud(cloudDiv ,Pname ,color){
getPersonDataCloud( cloudDiv,Pname ,color );
setInterval(function() {
// Do something every 5 minutes
getPersonDataCloud( cloudDiv,Pname ,color );
}, 300000);
}
function updatePersonText( newtext, cloudDiv,color){
var cloudDivID ="#"+cloudDiv;
var width = $(cloudDivID).width();
var height = $(cloudDivID).height();
console.log(JSON.stringify(newtext));
//var colorset =[color,"#6d4c41","#000000"];
//console.log(width);
var text={
"name": "wordcloud",
"width": width,
"height": height,
"padding": {"top":0, "bottom":0, "left":0, "right":0},
"data": [
{
"name": "table",
"values": newtext,
"transform": [
{
"type": "wordcloud",
"text": "data.text",
"font": "Helvetica Neue",
"fontSize": "data.value",
"rotate": {"random": [-90,-45,0,45,90]}
}
]
}
],
"marks": [
{
"type": "text",
"from": {"data": "table"},
"properties": {
"enter": {
"x": {"field": "x"},
"y": {"field": "y"},
"angle": {"field": "angle"},
"align": {"value": "center"},
"baseline": {"value": "alphabetic"},
"font": {"field": "font"},
"fontSize": {"field": "fontSize"},
"text": {"field": "data.text"}
},
"update": {
"fill": {"value": color}
},
"hover": {
"fill": {"value": "#f00"}
}
}
}
]
};
return text;
}
function getPersonDataCloud(cloudDiv, Pname,color){
var cloudDivID="#"+cloudDiv;
var newTestString=" ";
var JSONObj = new Object();
var Candidates = { Choose : Pname};
$.ajax({
url: "js/candidateCloud.jag",
dataType: "json",
contentType:'application/json',
data: JSON.stringify(Candidates),
type: "POST",
success: function (data) {
var TextData=JSON.stringify(data);
var res = TextData.split(";");
var jsonStr='{"values":[]}';
JSONObj=JSON.parse(jsonStr);
for(var i=1;i<res.length-1;i++){
var text=res[i];
var array= text.split(":");
var str= '{"text": "'+array[0]+'", "value":'+(array[1]*10)+'}';
JSONObj["values"].push(JSON.parse(str));
}
console.log(JSON.stringify(JSONObj["values"]));
var newcloud =updatePersonText(JSONObj["values"],cloudDiv,color);
console.log(JSON.stringify(newcloud));
var viewUpdateFunction = (function(chart) {
this.view = chart({el:cloudDivID}).update();
}).bind(this);
vg.parse.spec(newcloud, viewUpdateFunction);
}
});
}
Vega documentation states that "values" accepts JSON. In your situation the newtext is string some how. Try to replace the parsing code with below example.
...
$.ajax({
url: "js/candidateCloud.jag",
dataType: "json",
contentType:'application/json',
data: JSON.stringify(Candidates),
type: "POST",
success: function (data) {
var TextData=JSON.stringify(data);
var res = TextData.split(";");
//var jsonStr='{"values":[]}';
JSONObj=[];
for(var i=1;i<res.length-1;i++){
var text=res[i];
var array= text.split(":");
var str= '{"text": "'+array[0]+'", "value":'+(array[1]*10)+'}';
JSONObj.push(JSON.parse(str));
}
console.log(JSON.stringify(JSONObj["values"]));
var newcloud =updatePersonText(JSONObj,cloudDiv,color);
console.log(JSON.stringify(newcloud));
var viewUpdateFunction = (function(chart) {
this.view = chart({el:cloudDivID}).update();
}).bind(this);
vg.parse.spec(newcloud, viewUpdateFunction);
}
});
...
The div is appearing in the HTML, and the javascript also appears in the source... Any idea why I am still seeing nothing on the page?
NOTE: Manually running the js in the console causes the chart to render just fine
View:
<%= high_chart("some_id", #chart) %>
Controller:
#chart = LazyHighCharts::HighChart.new('graph') do |f|
f.title(:text => "Population vs GDP For 5 Big Countries [2009]")
f.xAxis(:categories => ["United States", "Japan", "China", "Germany", "France"])
f.series(:name => "GDP in Billions", :yAxis => 0, :data => [14119, 5068, 4985, 3339, 2656])
f.series(:name => "Population in Millions", :yAxis => 1, :data => [310, 127, 1340, 81, 65])
f.yAxis [
{:title => {:text => "GDP in Billions", :margin => 70} },
{:title => {:text => "Population in Millions"}, :opposite => true},
]
f.legend(:align => 'right', :verticalAlign => 'top', :y => 75, :x => -50, :layout => 'vertical',)
f.chart({:defaultSeriesType=>"column"})
end
Result in page view:
<script type="text/javascript">
(function() {
var onload = window.onload;
window.onload = function(){
if (typeof onload == "function") onload();
var options = { "title": { "text": "Population vs GDP For 5 Big Countries [2009]" },"legend": { "align": "right","verticalAlign": "top","y": 75,"x": -50,"layout": "vertical" },"xAxis": { "categories": [ "United States","Japan","China","Germany","France" ] },"yAxis": [ { "title": { "text": "GDP in Billions","margin": 70 } },{ "title": { "text": "Population in Millions" },"opposite": true } ],"tooltip": { "enabled": true },"credits": { "enabled": false },"plotOptions": { "areaspline": { } },"chart": { "defaultSeriesType": "column","renderTo": "some_id" },"subtitle": { },"series": [{ "name": "GDP in Billions","yAxis": 0,"data": [ 14119,5068,4985,3339,2656 ] },{ "name": "Population in Millions","yAxis": 1,"data": [ 310,127,1340,81,65 ] }] };
window.chart_some_id = new Highcharts.Chart(options);
};
})()
</script>
<div id="some_id"></div>