orgchart splitting into three, and displaying Id's on the chart - orgchart

Here's what my chart displays:
Here's my Position tables:
My position table
cant really seem to figure out whats the problem.
-Ive got a button and a dropdown, when an item is selected from the dropdown and button is selected an orgchart must be displayed. The chart displays but the problems are:
-orgchart splitting into three charts
-And it keeps showing some Id's
-here's my code:
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$("#btnGetOrganogram").on('click', function (e) {
debugger
$ddlDepOrgano = $('[id$="ddlDepOrgano"]').val();
if ($ddlDepOrgano != "") {
var jsonData = $.ajax({
type: "POST",
url: '/services/eleaveService.asmx/GetChartData',
data: "{'depid':'" + $ddlDepOrgano + "'}",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: OnSuccess_getOrgData,
error: OnErrorCall_getOrgData
});
function OnSuccess_getOrgData(repo) {
var data = new google.visualization.DataTable(jsonData);
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
var response = repo.d;
for (var i = 0; i < response.length; i++) {
var row = new Array();
var Pos_Name = response[i].Pos_Name;
var Pos_Level = response[i].Pos_Level;
var Emp_Name = response[i].Emp_Name;
var Pos_ID = response[i].Pos_ID;
var Emp_ID = response[i].Emp_ID;
data.addRows([[{
v: Emp_ID,
f: Pos_Name
}, Pos_Level, Emp_Name]]);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data,{ allowHtml: true });
}
function OnErrorCall_getOrgData() {
console.log("something went wrong ");
}
} else {
bootbox.alert("Invalid Department Name please try again.");
}
e.preventDefault();
});
}

according to the data format, Column 1 should be the ID of the manager, which is used to build the tree...
Column 1 - [optional] The ID of the parent node. This should be the unformatted value from column 0 of another row. Leave unspecified for a root node.
looking at the data table image posted, this should be in column --> Mngr_ID
as such, recommend the following changes when loading the data...
for (var i = 0; i < response.length; i++) {
var row = new Array();
var Pos_Name = response[i].Pos_Name;
var Emp_Name = response[i].Emp_Name;
var Emp_ID = response[i].Emp_ID;
var Mngr_ID = response[i].Mngr_ID;
data.addRow([
{
v: Emp_ID,
f: Pos_Name
},
Mngr_ID,
Emp_Name
]);
}

Related

Removing duplicates while loading a combo in HTML using a txt file

Below is my code to load the combo using a txt file:
$("#Combo1").change(function() {
$('#Combo2').empty();
$.ajax({
url: 'File.txt',
type: 'get',
success: function(txt){
var value = [];
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++)
{
var tmpData = txtArray[i].split(',');
if (!value[tmpData[1]])
{
value.push([tmpData[1]]);
value[tmpData[1]] = true;
}
}
$('#Combo2').empty();
$.each(value, function(i, p) {
$('#Combo2').append($('<option></option>').val(p).html(p));
});
}
})
});
$("#Combo1").trigger("change");
Here on change of Combo1, this will be called. The Ajax is used to read the content of File.txt File.txt has a "," seperated two columns, out of which I am willing to print coulmn2. Given below are the contents of File.TXT.
A,31JAN
B,25JAN
C,31JAN
D,6JAN
E,6JAN
I was to load the above dates in Combo2. With the above code, I am able to ignore 31JAN. But 6JAN is getting repeated. In short, the value which is given at the last row gets repeated. Rest is fine.
Try this:
var txt="A,31JAN\nB,25JAN\nC,31JAN\nD,6JAN\nE,6JAN";
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++)
txtArray[i] = txtArray[i].split(",").pop();
var value = txtArray.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]);
console.log(value); //returns array
Also, give this a read: https://stackoverflow.com/a/9229821/9920079 :)

Pass a function to kendo UI chart "data" element

Hi I am trying to display some data in a kendo UI bar chart , the data comes from an ASP.NET MVC action that returns json data.
Is it possible to pass a function to a kendo UI data element like the following ?
series: [{
name: "Oddo Avenir Euro CI-EUR",
data: GetFundPerfCalendSP,
border: {
width: 0
}
The function :
function GetFundPerfCalendSP(){
$(document).ready(function(){
var data;
var value = $("#idProduitSP").text();
var bechmarkArray = new Array();
var SpArray = new Array();
console.log(value);
$.ajax({
url:'../controllerName/actionname',
type:'POST',
datatype:'json',
data:{
idProduitSP:value
},
success :function(result)
data = result;
for(var i = 0; i < data.length; i++) {
SpArray.push(data[i].PerformanceSP*100);
}
console.log(SpArray);
return SpArray;
},
error:function(error){
console.log("ajax request failed");
}
});
});
}

DataStudio returns random error id when using custom connector

I am using script.google.com to create a custom connector that can read CSV data from drive.google.com and send the data to Googles data studio.
When running the connector and inserting a simple table inside the data studio, I receive a simple that the request could not be processed because of an server error. The error id is changing every time I "re-publish" the script.
This is
function getData(request) {
var dataSchema = [];
request.fields.forEach(function(field) {
for (var i = 0; i < csvDataSchema.length; i++) {
if (csvDataSchema[i].name === field.name) {
dataSchema.push(csvDataSchema[i]);
break;
}
}
});
csvFile = UrlFetchApp.fetch("https://drive.google.com/uc?export=download&id=" + request.configParams.documentId);
var csvData = Utilities.parseCsv(csvFile);
var data = [];
csvData.forEach(function(row) {
data.push({
values: row
});
});
console.log( {
schema: dataSchema,
rows: data
} );
return {
schema: dataSchema,
rows: data
};
};
This is the csvDataSchema:
var csvDataSchema = [
{
name: 'date',
label: 'Date',
dataType: 'STRING',
semantics: {
conceptType: 'DIMENSION'
}
},
{
name: 'nanoseconds',
label: 'nanoseconds',
dataType: 'NUMBER',
semantics: {
"isReaggregatable": true,
conceptType: 'METRIC'
}
},{
name: 'size',
label: 'Size of Testfile in MByte',
dataType: 'STRING',
semantics: {
"isReaggregatable": false,
conceptType: 'DIMENSION'
}
}
];
And this is the result of the getData function, stringified:
{"schema":[{"name":"date","label":"Date","dataType":"STRING","semantics":{"conceptType":"DIMENSION"}},{"name":"size","label":"Size of Testfile in MByte","dataType":"STRING","semantics":{"isReaggregatable":false,"conceptType":"DIMENSION"}}],"rows":[{"values":["2017-05-23",123,"1"]},{"values":["2017-05-23",123,"1"]}]}
It perfectly fits to the reference. I am providing more information, but following the tutorial it should work, anyways.
Those are the fields provided in request:
And this is what getDate returns:
So, what I am wondering first is: Why is there a random error id? And what could be wrong with my script?
You should only return fields/columns included in request. Currently, data contains all fields that are in csvFile. Depending on your chart element in your dashboard, request will most likely contain only a subset of your full schema. See example implementation at the Data Studio Open Source repo.
If this does not solve the problem, you should setup error handing and check if the error is occurring at any specific line.
#Minhaz Kazi gave the missing hint:
As I did not "dynamically" filled the response object in getData, I always returned all three columns.
With my code above the only thing I had to do is adding the third column as a dimension or a metric.
So I changed my code to dynamically return the columns so it will fit to the response. For this I had to implement an function that will transform the CSV-data into an object.
This is the getData() function now:
function getData(request) {
var url = "https://drive.google.com/uc?export=download&id="
+ request.configParams.documentId;
var csvFile = UrlFetchApp.fetch(url);
var csvData = Utilities.parseCsv(csvFile);
var sourceData = csvToObject(csvData);
var data = [];
sourceData.forEach(function(row) {
var values = [];
dataSchema.forEach(function(field) {
switch(field.name) {
case 'date':
values.push(row.date);
break;
case 'nanoseconds':
values.push(row.nanoseconds);
break;
case 'size':
values.push(row.size);
break;
default:
values.push('');
}
});
data.push({
values: values
});
});
return {
schema: dataSchema,
rows: data
};
};}
And this is the function to convert the CSV data to an object:
function csvToObject(array) {
var headers = array[0];
var jsonData = [];
for ( var i = 1, length = array.length; i < length; i++ )
{
var row = array[i];
var data = {};
for ( var x = 0; x < row.length; x++ )
{
data[headers[x]] = row[x];
}
jsonData.push(data);
}
return jsonData;
}
(it's based on a so-solution from here, I modified it to fit my source CSV data)

KendoGrid refresh

I'm using KendoGrid to display some data fetched from my service.
The user selects some parameters (company and date) and cliks on a load button.
The user selects a month on a datePicker and the server will return data from that date plus 11 months.
I only display the grid after the user click on the load button.
Load function:
function loadGrid(e) {
var companyIds = [1, 3, 7]; // user select it
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var rowHeaders = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
var _dataSource = function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: URL,
dataType: "json",
data: {
companyIds: companyIds,
date: kendo.toString(picker.value(), "yyyy-MM-dd") // user select it
}
}
},
schema: {
data: function (data) {
// function to handle data returned from server
var dataArray = [];
var index = 0;
for (var key in data[0]) {
if (Object.prototype.hasOwnProperty.call(data[0], key)) {
var property = key;
if (property == "date") {
continue;
}
key = {};
key["X"] = rowHeaders[index];
index++;
for (var i = 0; i < data.length; i++) {
var date = data[i].date;
var dateSplit = date.split("-");
var year = dateSplit[0];
var month = months[dateSplit[1] - 1];
var header = month + "_" + year;
key[header] = data[i][property];
}
dataArray.push(key);
}
}
return dataArray;
}
}
});
return dataSource;
};
$("#grid").kendoGrid({
scrollable: false,
editable: false,
dataSource: _dataSource()
});
}
When I click on the load button for the first time, the datasource is loaded and the grid is displayed correctly.
But, for instance, if I change the date on the datePicker and click on the load button again, the datasource is loaded with the correct data (new records for other months), but the grid is not refreshed.
If the first time I select the month Jan/2015, it loads and displays from Jan/2015 until Dec/2015, which is correct.
But if than I select the month Feb/2015, the datasource loads from Feb/2015 until Jan/2016 (correct), but the grid display the columns from Jan/2015 until Dec/2015, which is wrong. In this case, the column Jan/2015 is shown empty and the column Jan/2016 is not displayed.
Can someone point me to the right direction?
Thanks!
You should use a function for your dataSource -> transport -> read -> data:
data: function() {
return {
companyIds: companyIds,
date: kendo.toString(picker.value(), "yyyy-MM-dd") // user select it
};
}
UPDATE:
Here is how I would do it:
function loadGrid(e) {
$("#grid").data("kendoGrid").dataSource.fetch();
}
function getData() {
var companyIds = ...
var picker = ...
return {
companyIds: companyIds,
date: kendo.toString(picker.value(), "yyyy-MM-dd") // user select it
};
}
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: URL,
dataType: "json",
data: getData
}
},
schema: {
data: function (data) {
// function to handle data returned from server
var dataArray = [];
var index = 0;
for (var key in data[0]) {
if (Object.prototype.hasOwnProperty.call(data[0], key)) {
var property = key;
if (property == "date") {
continue;
}
key = {};
key["X"] = rowHeaders[index];
index++;
for (var i = 0; i < data.length; i++) {
var date = data[i].date;
var dateSplit = date.split("-");
var year = dateSplit[0];
var month = months[dateSplit[1] - 1];
var header = month + "_" + year;
key[header] = data[i][property];
}
dataArray.push(key);
}
}
return dataArray;
}
}
});
$("#grid").kendoGrid({
scrollable: false,
editable: false,
dataSource: dataSource
});
I ended up destroying and recreating the grid when the user clicks on load button.
$("#loadButton").kendoButton({
click: loadGrid
});
var loaded = false;
function loadGrid(e) {
if (value) {
if (loaded) {
var grid = $("#grid").data("kendoGrid");
grid.wrapper.empty();
grid.destroy();
}
$("#grid").kendoGrid({
scrollable: false,
editable: false,
autoBind: false,
dataSource: _dataSource()
});
$("#grid").data("kendoGrid").dataSource.read();
loaded = true;
} else {
e.preventDefault();
alert("aaaa");
}
}

Wordpress custom JSON feed with multiple categories

Good morning to all.
It is possible to have a custom JSON feed with the last 10 posts from all categories with 10 or more posts published?
I'm doing that with a loop over all categories with 10 or more posts published using the JSON API plugin for wordpress by dphiffer
So if I have 14 categories I will do 140 requests and overload the server.
I'm searching for a way to do that with 1 or 2 requests. Like first request to get the categories indexes with 10 or more posts and the second request with all the data.
Thanks
Here is the code i've developed so far:
<script type="text/javascript">
var slug = 'news'; // Main categorie
var maxLength = 10; // Total of articles per categorie
var wpurl = 'http://wpurl.com'; // WP URL
var loadedValue, loadedTotal;
var categories = new Array();
var newsData = new Array();
//Get main categorie index by slug
$.ajax({
url: wpurl+'/?json=get_category_index',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
if(cat.slug == slug) {
get_all_categories(cat.id);
}
}
},
error: function(data){
console.log(data);
}
});
//Get all sub-categories from an categorie slug
function get_all_categories(cat_index) {
$.ajax({
url: wpurl+'/?json=get_category_index&parent='+cat_index,
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
//Check if categorie have 10 (maxLength) or more posts. If so push it to array (categories)
if(cat.post_count >= maxLength) {
categories.push({
'index': cat.id,
'title': cat.title
});
}
}
},
error: function(data){
console.log(data);
}
}).done(function() {
//Set loading
var totalItem = categories.length*maxLength;
var actualItem = 0;
var loaded = 0;
for(var i=1; i<=categories.length; i++){
prepareCategory(categories[i-1].index, maxLength, i);
function prepareCategory(categorieIndex, maxLenght, count) {
var content;
$.ajax({
url: wpurl+'/api/get_category_posts?category_id='+categorieIndex+'&count='+maxLenght+'&status=publish',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (e = 0; e < data.posts.length; e++) {
//Loading percent
actualItem++;
loaded = (actualItem/totalItem)*100;
document.getElementById('loadingBox').innerHTML = 'Loading: '+Math.round(loaded)+'%';
//Post data
var post = data.posts[e];
var title = post.title;
var thumb = post.thumbnail_images.appthumb.url || 'content/images/noimage.png';
var newContent = '<div class="new"><img src="'+thumb+'" width="320" height="164"><div class="new_description">'+title+'</div></div>';
var newId = 'cat'+count+'new'+(e+1);
newsData.push({
'id': newId,
'content':newContent
});
}
},
error: function(data){
console.log(data);
}
});
}
}
});
};
function loaded() {
if (window.localStorage.length != 0)
{
localStorage.clear();
setGlobalStorageAndRedirect();
} else {
setGlobalStorageAndRedirect();
}
function setGlobalStorageAndRedirect() {
localStorage.setItem('postPerCat', maxLength);
localStorage.setItem('catNumbs', categories.length);
localStorage.setItem('wpurl', wpurl);
localStorage.setItem('categoriesArray', JSON.stringify(categories));
localStorage.setItem('newsData', JSON.stringify(newsData));
window.location="main.html";
}
}
</script>