Organization Chart from sharepoint list items - javascript

I want to create an organization chart which I want to populate using the values from a sharepoint list. I would like to retrieve items using REST and Javascript. Here is my code. It in partially working, but cannot create a chart. Please help someone.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
debugger;
$.ajax({
url: "http://myurl/_api/Web/Lists/GetByTitle('Employee Hierarchy')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (r) {
debugger;
var items = r.d.results;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i <items.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: employeeName + '<div>(<span>' + designation + '</span>)</div><img src = "Pictures/' + employeeId + '.jpg" />'
}, reportingManager, designation]]);
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart">
</div>
this is the structure of my sharepoint list

The following example demonstrates how to visualize SharePoint List data as organization chart via Google Visualization API
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(displayChart);
function displayChart()
{
loadListItems('Employee Hierarchy')
.done(function(data){
var items = data.d.results;
drawChart(items);
})
.fail(function(error){
console.log(error);
});
}
function drawChart(items) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < items.length; i++) {
data.addRow([items[i]['Title'],items[i]['Manager']['Title'],'']);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
function loadListItems(listTitle){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/items?$select=Title,Manager/Title&$expand=Manager",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
Key points
In my example the list has the following schema:
Field Name Type
Title Text
Manager Lookup
Description Note
List view page
Resulting page

Related

How to show full tree from particular parent in javascript with c#

we are trying to show HierarchyTrees from database without any condition it show's fine.
but when we apply condition for particular user, then showing only root's three child but not showing child's sub child.
i have created one InputBox, by using InputBox i passed the Parent Id with condition, but it showing only three childs not showing full tree .
This is Front end code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="chart">
</div>
<input type="text" id="txtSearch" runat="server" value="t" clientidmode="Static" />
</asp:Content>
This is Javascript code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "WebForm21.aspx/GetChartData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < r.d.length; i++) {
var memberId = r.d[i][0].toString();
var memberName = r.d[i][1];
var sp = r.d[i][3];
var parentId = r.d[i][2].toString() ? r.d[i][2].toString() : '';
data.addRows([[{
v: sp,
f: memberName + '<div><img src = "Pictures/' + memberId + '.jpg" /></div>'
}, parentId, memberName]]);
}
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
This is Backend code
[WebMethod]
public static List<object> GetChartData(string username)
{
string query = "SELECT RegionLoginOID, RegionName, SponserID,Child_Id";
query += " FROM RegionLogin where SponserID LIKE ''+#SponserID+'%' ";
using (SqlConnection con = ClsConnection.Connections())
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("#SponserID", username);
List<object> chartData = new List<object>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["RegionLoginOID"], sdr["RegionName"], sdr["SponserID"], sdr["Child_Id"]
});
}
}
return chartData;
}
}
}

Google Charts Dashboard, AJAX call fails to load data from SQL DB

Ive been trying to load data from a SQL table thats generated daily via a SP, Table consists of 4 columns.
My Ajax call gets the data and puts into an array -
Array
Heres my code im using to draw the view and pass the array -
var chartData;
$(document).ready(function () {
$.ajax({
url: "/Reporting/LeaveList",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
//console.log(data);
console.log(typeof data);
chartData = data;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
google.setOnLoadCallback(createTable);
});
});
function createTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'AnnualLeave');
data.addColumn('number', 'Sick');
data.addColumn('number', 'Total');
data.addRow(chartData[0])
// Create a dashboard.
var dash_container = document.getElementById('dashboard_div'),
myDashboard = new google.visualization.Dashboard(dash_container);
// Create a date range slider
var myDateSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control_div',
'options': {
'filterColumnLabel': 'Date'
}
});
// Table visualization
var myTable = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div'
});
// Bind myTable to the dashboard, and to the controls
// this will make sure our table is update when our date changes
myDashboard.bind(myDateSlider, myTable);
// Line chart visualization
var myLine = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'line_div',
});
// Bind myLine to the dashboard, and to the controls
myDashboard.bind(myDateSlider, myLine);
myDashboard.draw(data);
And heres some of the controller -
data = (
from u in db.StaffReportingDay
select new StaffReportingDayVM
{
Date = u.Date.ToString(),
AnnualLeave = u.AnnualLeave,
CompassionateLeave = u.CompassionateLeave,
Sick = u.Sick,
StudyLeave = u.StudyLeave,
Total = u.Total
}).ToList();
}
var ChartOne = new object[data.Count + 1];
ChartOne[0] = new object[]
{
"Date",
"Annual Leave",
"Sick Leave",
"Total on Leave"
};
int j = 0;
foreach(var i in data)
{
j++;
ChartOne[j] = new object[] {i.Date.ToString(), i.AnnualLeave, i.Sick, i.Total };
}
return Json(ChartOne, JsonRequestBehavior.AllowGet);
What i cant get is the array to pull into the view, i just get an error -
Uncaught Error: Type mismatch. Value Annual Leave does not match type number in column index 1
Ive tried many things but would like some pointers and other people to give their insight please.
Solved with
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'AnnualLeave');
data.addColumn('number', 'CompassionateLeave');
data.addColumn('number', 'StudyLeave');
data.addColumn('number', 'Sick');
data.addColumn('number', 'Total');
$.each(chartData, function (i, row) {
data.addRow([
(new Date(row.Date)),
parseFloat(row.AnnualLeave),
parseFloat(row.CompassionateLeave),
parseFloat(row.StudyLeave),
parseFloat(row.Sick),
parseFloat(row.Total)
]);
});

how to prevent javascript function to execute when page is postback?

I have this java script code that generate organizational chart from database
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "add org unit.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < r.d.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[
i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: '<a target="_blank" href="edit emp cv.aspx?employeeId='+employeeId+'">' + employeeName + '</a>' + '<div><span>' + designation + '</div></span>',
}, reportingManager, designation]]);
}
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
and these web method in c# code behind
[WebMethod]
public static List<object> GetChartData()
{
DataLayer.StoreDBEntities dbEntities = new DataLayer.StoreDBEntities();
List<object> chartData = new List<object>();
List<DataLayer.org_unit> result = dbEntities.org_unit.ToList();
foreach (DataLayer.org_unit unit in result)
{
string name = unit.org_unit_type.alias + " " + unit.name;
string Details = "";
if (unit.emp_assignment.ToArray().Length != 0)
{
List<DataLayer.emp_assignment> empAssigns = unit.emp_assignment.ToList();
foreach (DataLayer.emp_assignment assign in empAssigns)
{
Details += assign.job_title.alias + ":" + assign.employee.name + "<br/>";
}
}
chartData.Add(new object[] { unit.id, name, Details, unit.upper_unit_id });
}
return chartData;
}
the chart is regenerated every postback and when page is load
although I did not call java script function at all
how to stop this ? i want to generate chart only whene butten click
First, you need to remove this google.setOnLoadCallback(drawChart); then you can use the jQuery click event like this:
$(function() {
$('#draw-chart').click(function(event) {
event.preventDefault();
drawChart();
});
});
Add a button to your HTML like this:
<button id="draw-chart">Draw Chart</button>

filter by a key/value from json Array

here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});

Connect Array to Google Chart

I've been trying for ages to try and connect this array to a google chart and having no luck, would really appreciate some help to locate what I've done wrong. I have a jsfiddle going, and you can see that the array is fine, if copied and pasted to the chart manually it works, so it's just a code issue of not making it through.
http://jsfiddle.net/DNH5n/8/
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataset = $.ajax({
url: 'http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?page=1',
type: 'get',
dataType: 'jsonp',
crossDomain: true,
success: function (jsonObj) {
var arr = ["[['Time', 'Humidity', 'Temp']"];
$.each(jsonObj, function (i, tObj) {
arr.push("['" + tObj.stationtime + "', " + tObj.humidity + ', ' + tObj.temp + ']');
});
arr.push("]")
// This for debugging
document.getElementById("demo").innerHTML = arr;
}
});
var data = google.visualization.arrayToDataTable([
dataset
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
A couple of things:
You can't use an AJAX call as the input to arrayToDataTable. You have to use the result of the AJAX call.
Parse the output of the AJAX call, and put them into Date objects, and floats.
Check out the following:
http://jsfiddle.net/K8bk3/
$.ajax({
url: 'http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?page=1',
type: 'get',
dataType: 'jsonp',
crossDomain: true,
success: function (jsonObj) {
var arr = [['Time', 'Humidity', 'Temp']];
$.each(jsonObj, function (i, tObj) {
arr.push([new Date(tObj.stationtime), parseFloat(tObj.humidity), parseFloat(tObj.temp)]);
});
document.getElementById("demo").innerHTML = arr;
var data = google.visualization.arrayToDataTable(arr);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options); }
});

Categories