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>
Related
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;
}
}
}
My scenario is; I'm trying to do a live search feature for my ASP.net project. In the form, I have a description textbox where the user will type in the search and as the user types in anything, the GridView below filters the results accordingly. I have tried this on desktop applications and it's not much of a hassle but I recently dipped in on Web Applications. Any help would be appreciated. I'm sure there is an easy way to do this but I seem to be having trouble finding "that" way.
Below are what I tried already:
I have tried using onTextChanged property of the textbox but it only populates after the event request.
I have added a function using Ajax+ JQuery which calls the method but the gridview is not displaying the data.
enter code here
<script type="text/javascript">
$(function () {
GetCustomers();
});
$("[id*=TxtDescription]").live("keyup", function () {
GetCustomers();
});
function SearchTerm() {
return jQuery.trim($("[id*=TxtDescription]").val());
};
function GetCustomers() {
$.ajax({
type: "POST",
url: "frmDrugMaster.aspx/GetCustomers",
data: '{searchTerm: "' + SearchTerm() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
var row;
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Drugs");
alert(customers.length);
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
alert(customers.length);
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("DR_Code").text());
$("td", row).eq(1).html($(this).find("DR_Description").text());
$("td", row).eq(2).html($(this).find("DR_UnitDose").text());
alert($("td", row).eq(0).html($(this).find("DR_Description").text()));
$("[id*=gvCustomers]").append(row);
$
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(row);
}
};
</script>
[WebMethod]
public static string GetCustomers(string searchTerm)
{
SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT a.DR_UNITDOSE, a.DR_CODE, a.DR_DESCRIPTION, a.DR_GENERIC1, a.DR_GENERIC2, a.DR_GENERIC3, a.DR_GENERIC4, a.DR_COSTPRICE, a.DR_SELLPRICE, a.DR_STATUS FROM DRUGMASTER a, DRUGCATEGORY b where a.DR_CATEGORY = b.DC_CODE and DR_DESCRIPTION='"+ searchTerm + "' ", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
DataTable dt = new DataTable();
dt.TableName = "Drugs";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds.GetXml();
}
I found a solution to this or atleast a sort to workaround it. I used AJAX + JQuery. I just created a web service for the particular page where the text change will be applied. The codes used are as follows. Hope this helps someone:
/*form*/
create a webform with a textbox and a gridview:
/*Add this script*/
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
script type="text/javascript">
$(function () {
$("[id*=txtCountry]").on("keyup", function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetCustomers",
data: '{searchTerm: "' + $(this).val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var row;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Customers");
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
$.each(customers, function () {
$("td", row).eq(0).html($(this).find("PD_FSTNM").text());
$("td", row).eq(1).html($(this).find("PD_GENDER").text());
$("[id*=gvCustomers]").append(row);
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(empty_row);
}
},
failure: function (response) { alert(response.d); },
});
});
});
</script>
/*C# Code*/
[System.Web.Services.WebMethod]
public static string GetCustomers(string searchTerm = "")
{
string strConnString = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string query = "SELECT * FROM patientdetails";
if (!string.IsNullOrEmpty(searchTerm))
{
query += " WHERE PD_FSTNM LIKE '" + searchTerm + "%'";
}
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "Customers");
return ds.GetXml();
}
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
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); }
});
This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});