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); }
});
Related
I want a while loop that iterates if the amount paid is greater than zero. But running the code crashes the browser.
var amount = Number($('#payment1').val());
while (amount > 0){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
function xyz(amount){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
if(amount>0)
xyz(amount);
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
var amount = Number($('#payment1').val());
xyz(amount);
Try something like this. Instead of looping recursion is used.
Add async:false
var amount = Number($('#payment1').val());
while (amount > 0){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
async:false,
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
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>
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';
});
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 have a 'ng-grid' table that have 2 types of data source. One is from my database using a function called getContributors(), and another one is from a list of api(s).
The getContributors function is like the default function in the ng-grid tutorial.
function getContributors() {
var deferred = $q.defer();
$http.get(contributorsFile)
.then(function(result) {
contributors = result.data;
deferred.resolve(contributors);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
My method for loading the multiple api data is to load the database data first, and then after all the database data is all loaded it will make a request to the api using a parameter from the database data
var ajax_wait_count = 0;
gridService.getContributors().then(function(data) {
// Looping each data with angular.forEach()
angular.forEach(data, function(value, key){
var this_uid = value['uid'];
// if(ajax_wait_count==0)
// {
$timeout(function(){
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getrank.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['ranked_tier'] = json;
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlevel.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['level'] = json['level'];
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getsummonercreate.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != 0) {
var date_c = json[0]['create_date'];
date_c = date_c.replace(' ', 'T');
new_date = new Date(date_c);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['summoner_create_date'] = datestring;
}
else if (json == 0) {
data[key]['summoner_create_date'] = "";
}
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlastplayed.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != "null" && json != null) {
var datedatas = json;
var datearray = [];
var thedatestr = "";
var loopidx = 1;
now_date = new Date();
now_date.setHours(0);
now_date.setMinutes(0);
now_date.setSeconds(0);
now_date.setDate(now_date.getDate() - 2);
next_date = new Date();
next_date.setHours(23);
next_date.setMinutes(59);
next_date.setSeconds(59);
// next_date.setDate(next_date.getDate());
angular.forEach(datedatas, function (value3, key3) {
datearray[key3] = parseInt(value3['createDate']);
});
datearray.sort();
datearray.reverse();
var count_played_today = 0;
angular.forEach(datearray, function (value2, key2) {
if (loopidx == 1) {
thedatestr = value2;
}
date_compare = new Date(parseInt(value2));
if (date_compare.getTime() >= now_date.getTime() && date_compare.getTime() < next_date.getTime()) {
count_played_today++;
}
loopidx++;
});
// var date_c = json[0]['create_date'];
// date_c = date_c.replace(' ','T');
var dateinsert = parseInt(thedatestr);
new_date = new Date(dateinsert);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['last_played_date'] = datestring;
this_date = new Date();
date_diff = dateDiff(new_date.toString(), this_date.toString());
data[key]['last_played_date_qty'] = date_diff.d + " days " + date_diff.h + " hours " + date_diff.m + " minutes";
data[key]['count_played'] = count_played_today;
}
else if (json == "null" || json == null) {
data[key]['last_played_date'] = "";
data[key]['last_played_date_qty'] = "";
data[key]['count_played'] = 0;
}
},
error: function () {
// alert("Error");
}
});
},1500);
ajax_wait_count=0;
// }
ajax_wait_count++;
});
$scope.myData = data;
});
Now, the problem that emerges is :
The loading time for the api data is very long, and because of ajax asynchronous request, I can't make a loading function to delay the data
It appends the api data after the database data, which sometimes confuses the user whether the data is loaded or not
Sometimes in Chrome, the request is too much and it returns "err_insufficient_resources"
My question is,
Can my method of loading the api data be changed so it will make the loading time much faster and more efficient?
To make users less confused about the high amount of data, how can I make the progressbar (angular progress bar) wait for the database data + the api (AJAX) data?
Thank you in advance